开发者

how to get data from mysql in php based on url?

开发者 https://www.devze.com 2023-02-26 21:36 出处:网络
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

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


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"]; 


  1. Connect to the database server and select a datbase (e.g. using mysql_connect and mysql_select_db)
  2. Create a SQL query using values from the $_GET array
  3. Send the query to the database (e.g using mysql_query)
  4. Retrieve the result (e.g. using mysql_fetch_array)
  5. Display the data from the result (e.g. using echo)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消