PDO 显示数据库中每个特定 ID 的数据 [英] PDO displaying data from database foreach specific ID
问题描述
如果会员登录,他们的网址就像 index.php?id=5
if member logon they have url like index.php?id=5
$id = $_GET['id']
我可以通过这样做来显示用户数据
I can show the user data by doing this
$pdo = Database::connect();
$sql = 'SELECT * FROM data WHERE id_member = "5" ORDER BY tgl DESC';
foreach ($pdo->query($sql) as $row) {
echo '<td>'. $row['tgl'] . '</td>';
}
但如果我改成这样,什么都不会发生.
but if i change to this, nothing happen.
$pdo = Database::connect();
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = $id ORDER BY tgl DESC');
$q->bindValue(':id', $id, PDO::PARAM_INT);
foreach ($pdo->query($q) as $row) {
echo '<td>'. $row['tgl'] . '</td>';
}
但我不明白.有人可以帮我吗?请给我正确的代码并解释一下,我是 PDO 的新手.
but i dont understand. can somebody help me please? give me right code and explain it please, iam new with PDO.
谢谢
推荐答案
在您的语句中,您使用的是准备好的查询,因此您的查询看起来应该有所不同:
In your statement you are using a prepared query, therefore your query should look different:
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = :id ORDER BY tgl DESC');
您还必须在绑定参数后执行查询,如下所示:
You also have to execute your query after you bind the parameters, like so:
$q->execute();.
这样做应该可以解决您的问题:
So doing this should fix your problem:
$pdo = Database::connect();
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = :id ORDER BY tgl DESC');
$q->execute(['id'=>$id])
foreach ($q as $row) {
echo '<td>'. $row['tgl'] . '</td>';
}
使用预处理语句通常是更好的做法,因为它们可以防止 sql 注入攻击.
It is generally better practice to use prepared statements as they prevent sql injection attacks.
这篇关于PDO 显示数据库中每个特定 ID 的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!