i have a page table in mysql db with 'page_name', 'title', content, 'author' fields. I want to get it with php like http://www.domain.com/index.php?page=page_name . How do i do it ? pls help
3 Answers
Access the GET parameter using the super global $_GET array:
$pagename = $_GET['page'];
Then write a query for the database. Note that you have to escape every data that comes from the outside:
$sql = "SELECT * FROM page_table WHERE page_name = '%s' LIMIT 1";
$sql = sprintf(%sql, mysql_real_escape_string($pagename));
Then execute the query and check that it worked.
$result = mysql_query($sql);
if(!$result) {
    // error occured
}
Use the function mysql_fetch_assoc to access the data:
$data = mysql_fetch_assoc($result);
You can now access all data in this asscociative array:
echo $data["title"]; 
 
    
    - 33,545
- 8
- 78
- 87
- Connect to the database server and select a datbase (e.g. using mysql_connect and mysql_select_db)
- Create a SQL query using values from the $_GETarray
- Send the query to the database (e.g using mysql_query)
- Retrieve the result (e.g. using mysql_fetch_array)
- Display the data from the result (e.g. using echo)
 
    
    - 31,254
- 3
- 43
- 68
You could do something like this:
<?php
   // get page
   $page_name = $_GET["page"];
   // Do the query
   $q = mysql_query("SELECT * FROM `pages_table` WHERE `page_name` LIKE '$page_name'");
   // loop the get the results
   while($result = mysql_fetch_assoc($q){
       $db_title = $result["title"];
       $db_content = $result["content"];
       $db_author = $result["author"];
   }
   //put the data together and echo
   echo "
      <h1>$db_title</h1>
      <p>$db_content</p>
      <h3>Author: $db_author</h3>
   ";
?>
Dont forget to connect to the db first! And do some checks on the $_GET[] for sql injections!!
EDIT
Depends on your php installation. If you don't have magic quotes enabled you could do something like $page_nameClean = addslashes($page_name); when you do a query or if you know that you are only going to use numbers to get the page (ex: domain.com?page=1232) you could do a check:
if(is_numeric($page_name)){
   // get the page out of the DB
}else{
   // Show an error message
}
Or have a look at this: avoid code injections
- 
                    1how do i perform checks on $_GET[] ? could you pls give me example code ? – ktm Apr 16 '11 at 11:40
 
     
    