如何使用PDO

时间:2015-04-30 09:44:44

标签: php mysql pdo

我想从我的数据库中提取项目的标题和价格并将它们变成变量 - $ title和$ price,以便我可以在代码中的其他位置使用它们。

以下是我的发言:

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

谁能告诉我怎么做?

4 个答案:

答案 0 :(得分:3)

您需要在->execute()之后获取结果。并且,请正确使用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'];
}

答案 1 :(得分:1)

$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'];

答案 2 :(得分:1)

你有没看过prepared statements

此解决方案适用于1个以上的结果。

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

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

答案 3 :(得分:1)

$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()你的vars。