Reputation: 285
I want to pull title and price of an item from my database and turn them into variables - $title and $price so that I can use them elsewhere in the code.
Here is my statement so far:
$sth = $dbh->prepare("SELECT title, price FROM book WHERE b_id=$book");
$sth->execute();
Can anyone tell me how to do this?
Upvotes: 2
Views: 85
Reputation: 26
$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'];
It's PDO so dont forget to bindParam() your vars.
Upvotes: 1
Reputation: 41885
You'll need to fetch results after ->execute()
tion. And please, use the API properly, when you're using prepared statements, bind the variables, don't use your variables straight up on the query string.
Prepare the statement including those placeholders.
$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'];
}
Upvotes: 3
Reputation: 6679
Did you look into prepared statements?
This solution is for more than 1 result.
$title=array();
$price=array();
while ($row = $stmt->fetch()) {
$title[]=$row['title'];
$price[]=$row['price'];
}
If you need it for 1 price and title, check ghost his answer.
Upvotes: 1
Reputation: 2447
$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'];
Upvotes: 1