如何使用 PDO 将数据库中的字段转换为变量

How do I turn fields from my database into variables using PDO

我想从我的数据库中提取商品的标题和价格并将它们转换为变量 - $title 和 $price 以便我可以在代码的其他地方使用它们。

到目前为止,这是我的声明:

$sth = $dbh->prepare("SELECT title, price FROM book WHERE b_id=$book");
$sth->execute();

谁能告诉我怎么做?

$sth = $dbh->prepare("SELECT `title`, `price` FROM `book` WHERE `b_id`='".$book."'");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$title=$result['title'];
$price=$result['price'];

您需要在 ->execute()tion 之后获取结果。请正确使用 API,当您使用准备好的语句时,绑定变量,不要直接在查询字符串上使用您的变量。

准备包含这些占位符的语句。

$sth = $dbh->prepare('SELECT title, price FROM book WHERE b_id = :book');
$sth->bindValue(':book', $book);
$sth->execute();
$results = $sth->fetch(PDO::FETCH_ASSOC);
if(!empty($results)) {
    $title = $results['title'];
    $price = $results['price'];
}

你调查过 prepared statements 了吗?

此解决方案适用于超过 1 个结果。

$title=array();
$price=array();
while ($row = $stmt->fetch()) {
    $title[]=$row['title'];
    $price[]=$row['price'];
}

如果您需要 1 个价格和标题,请查看 ghost 他的答案。

$sth = $dbh->prepare("SELECT title, price FROM book WHERE b_id=:book");
$sth->bindParam(":book",$book);
$sth->execute();

$result = $sth->fetch(PDO::FETCH_ASSOC);

$title=$result['title'];
$price=$result['price'];

这是 PDO 所以不要忘记 bindParam() 你的变量。