从数据库中为打开同一页面的每个列表项获取不同的数据


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

我有一个index.php文件和一个details.php文件,这两个文件都从同一个表products中检索数据。index.php文件显示了使用的产品名称列表

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

现在在details.php中,我只想显示我点击其名称的产品的详细信息。我该如何实现这一点?

在链接中传递名称,然后在下一页上使用参数化查询,只获取该记录。

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

在下一页:

$stmt = $mysqli->prepare('SELECT * FROM products where name = ? limit 1');
$stmt->bind_param("s", $_GET['name']);
$stmt->execute();
$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.

你应该在数据库中有一个主键,并将其放在你的url détails.php中,而不是传递你的产品名称