Arpan Dang Arpan Dang - 2 years ago 64
SQL Question

Fetch different data from the database for every list item which opens the same page

I have an index.php file and a details.php file, both of which retrieves data from the same table, products.
The index.php file shows a list of name of products using

$result = $mysqli->query('SELECT name FROM products');
while($obj = $result->fetch_object())
echo '<li><a href="details.php>'.$obj->name.'</a></li>';

Now in details.php, i only want to display the details of the product whose name i clicked on. How do I achieve this?

Answer Source

Pass the name in the link then use a parameterized query on the next page and get just that record.

echo '<li><a href="details.php?name=' . urlencode($obj->name) . '">'.$obj->name.'</a></li>';

on subsequent page:

$stmt = $mysqli->prepare('SELECT * FROM products where name = ? limit 1');
$stmt->bind_param("s", $_GET['name']);
$res = $stmt->get_result();
$row = $res->fetch_assoc();
print_r($row); // or whatever you want to do with it, indexes will be by name because is associative.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download