[英](PDO) Gather specific data from id
i Have an url stands as : http://website.com/update.php?id= {NUMBER}我有一个网址: http ://website.com/update.php?id= {NUMBER}
How would I make PDO grabs the results from that specific id?我将如何让 PDO 从该特定 ID 中获取结果?
Here is my attempt for update.php page :这是我对 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();
}
?>
To avoid this kind of mistakes you need to use prepared statements
of PDO
(which also prevents SQL INJECTION
)为了避免这种错误,您需要使用
PDO
的prepared statements
(这也可以防止SQL INJECTION
)
$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
I assume your ID is a number so don't use = 'id'
我假设您的 ID 是一个数字,所以不要使用
= 'id'
also you should use prepared statments to protect against SQL injection attacks您还应该使用准备好的语句来防止SQL 注入攻击
$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) {
...
}
I think your error is that in your SQL, your quotes are a bit mixed up... 我认为您的错误是在您的SQL中,您的引号有点混乱...
$sql = "SELECT * FROM users WHERE id = '. $id .'";
Will most likely give you a SQL statement which will be something like.. 很有可能会给您一条SQL语句,类似于。
SELECT * FROM users WHERE id = '. 1 .'
You should use prepared statements and bind variables as in others have pointed out, but in this case... 您应该像其他人指出的那样使用准备好的语句并绑定变量,但是在这种情况下...
$sql = "SELECT * FROM users WHERE id = $id";
Should work. 应该管用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.