user1636130
user1636130

Reputation: 1683

PHP MySQLi - Return a single value from a query with bound parameters?

This is probably an extremely simple question, but i just cant find the answer anywhere!

I have a query that returns one row from my database. I'm using mysqli to bind parameters and then execute it like so:

$sql_query = $mysqli->prepare("SELECT ID FROM `Author` WHERE `Name` = ? LIMIT 1;");
$sql_query->bind_param('s', $author);
$sql_query->execute();
$sql_query->store_result();
$sql_query->bind_result($authorID);

I want to store the ID into a variable to use in another query but its not working. The only way ive got it to work is with a while loop like so:

while($sql_query->fetch()){
    echo "ID: $authorID";
}

But because there is only ever one row, i dont want to use a while loop. How can i use the result variable without the while loop?

Upvotes: 1

Views: 587

Answers (1)

Fabio
Fabio

Reputation: 23480

I think you just need to fetch the row from the table

$sql_query->bind_result($authorID);
$sql_query->fetch();

Now you are able to print your value

echo $authorID;

Upvotes: 1

Related Questions