2

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?

1
  • I haven't specified or declared any variables yet. I want to put the results for title and price from the SELECT query into a new variable. Does that make sense? Commented Apr 30, 2015 at 9:49

4 Answers 4

3

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'];
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Enjoyted it defeats the purpose of having it prepared, thats why you use prepared statements, you bind the variables, not using them directly into the query
Well yeah, just said that because you answer was after Vicky's one but was overall better.
This is exactly what I was looking for, thanks. I understand why it's important to bind now.
@stark yes, always remember to bind those values when using prepare. glad this helped
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'];

1 Comment

maybe you should use the binding. like 'WHERE b_id = ?; $sth->execute(array($book));
1

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.

Comments

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

It's PDO so dont forget to bindParam() your vars.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.