stark
stark

Reputation: 285

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

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

Answers (4)

Yinka
Yinka

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

Kevin
Kevin

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

Loko
Loko

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

Vivek Singh
Vivek Singh

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

Related Questions