2

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 3

4

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"]; 
Sign up to request clarification or add additional context in comments.

Comments

1
  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)

Comments

1

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

1 Comment

how do i perform checks on $_GET[] ? could you pls give me example code ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.