简体   繁体   中英

PHP GET Rows based on URL ID

I have a search function on my site which displays results from a MySQL db. Each search result is linked to a dynamic php page with the URL, ie /details.php?id=123.

I need the details.php page to get the ID (eg 123) from the URL and then fetch all rows from the database with this ID, storing them in a variable for use later. I then need to be able to echo the rows at various points throughout the page to populate the content.

The code I have so far is:

<?php
$db = mysql_connect("","","") or die("Database Error");
mysql_select_db("items",$db); 
$id = $_GET['id']; 
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `items- table` WHERE `id`='" . $id . "'";  
$result = mysql_query($query); 
?>

I'm fairly new to PHP so not sure if the code above will get all rows based on the ID, and then how to echo the rows within divs on the page?

Almost correct. Just add something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo '<div>';
  foreach ($row as $key => $val) {
    echo $key.' = '.$value.'<br/>';
  }
  echo '</div>';
}

You can use mysql_fetch_array() OR mysql_fetch_assoc() function with while loop (if multiple rows there) OR without while loop if there is only one row.

$query = "SELECT * FROM `items- table` WHERE `id`='" . $id . "'";  
$result = mysql_query($query); 
while($fetch = mysql_fetch_array($result))
{
   echo "<div>".$fetch['column_name']."</div>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM