我有一个网址代表: http://website.com/update.php?id= {NUMBER}
如何让PDO从特定ID中获取结果?
这是我对update.php页面的尝试:
try {
$dbh = new PDO("mysql:host=$hostname;dbname=vector",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = '. $id .'";
foreach ($dbh->query($sql) as $row)
{
?>
<?php echo $row['username']; ?>
<?php
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
答案 0 :(得分:2)
注意: -
查询$sql = "SELECT * FROM users WHERE id = '. $id .'";
错误
需要: - $sql = "SELECT * FROM users WHERE id =$id";
但请尝试使用prepared statements
的 PDO
来阻止SQL INJECTION
try {
$dbh = new PDO("mysql:host=$hostname;dbname=vector",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$id = $_GET['id'];
$sth = $dbh->prepare("SELECT * FROM users WHERE id = ?");
$sth->execute(array($id));
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // check values are coming or not and then try to print it
$dbh = null;
}catch(PDOException $e){
echo $e->getMessage();
}
答案 1 :(得分:1)
我认为您的错误是在您的SQL中,您的报价有点混淆......
$sql = "SELECT * FROM users WHERE id = '. $id .'";
很可能会给你一个类似......的SQL语句。
SELECT * FROM users WHERE id = '. 1 .'
您应该像其他人指出的那样使用预准备语句和绑定变量,但在这种情况下......
$sql = "SELECT * FROM users WHERE id = $id";
应该工作。
答案 2 :(得分:0)
我认为您的ID是一个数字,所以不要使用= 'id'
您也应该使用准备好的声明来防范SQL injection attacks
$sql = "SELECT * FROM users WHERE id = :id";
$bind = array( 'id' => $id );
$sth = $dbh->prepare($sql);
$sth->execute($bind);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
...
}