Question

I'm trying to change my SQL queries with prepared statements. The idea: I'm getting multiple records out of the database with a while loop and then some additional data from the database in the loop.

This is my old SQL code (simplified):

$qry = "SELECT postId,title,userid from post WHERE id='$id'"; 
$rst01 = mysqli_query($mysqli, $qry01);
// loop trough mutiple results/records
while (list($postId,$title,$userid) = mysqli_fetch_array($rst01)) {
// second query to select additional data
$query05 = "SELECT name FROM users WHERE id='$userid";
$result05 = mysqli_query($mysqli, $query05);
$row05 = mysqli_fetch_array($result05);
$name = $row05[name ];

echo "Name: ".$name;

// do more stuff

// end of while loop
}

Now I want to rewrite this with prepared statements. My question: is it possible to run a prepared statement in the fetch of another prepared statement ? I still need the name like in the old SQL code I do for the $name.

This is what've written so far.

$stmt0 = $mysqli->stmt_init();
$stmt0->prepare("SELECT postId,title,userid from post WHERE id=?"); 
$stmt0->bind_param('i', $id);
$stmt0->execute();
$stmt0->bind_result($postId,$title,$userid);
// prepare second statement
$stmt1 = $mysqli->stmt_init();
$stmt1->prepare("SELECT name FROM users WHERE id= ?");
while($stmt0->fetch()) {

$stmt1->bind_param('i', $userid);
$stmt1->execute();
$res1 = $stmt1->get_result();
$row1 = $res1->fetch_assoc();

echo "Name: ".$row1['name'] ;

}

It returns an error for the second statement in the loop:

 Warning: mysqli_stmt::bind_param(): invalid object or resource mysqli_stmt in ... 

If I use the old method for the loop and just the prepared statement to fetch the $name it works.

Was it helpful?

Solution

You can actually do this with a single JOINed query:

SELECT p.postId, p.title, p.userid, u.name AS username
FROM post p
JOIN users u ON u.id = p.userid
WHERE p.id = ?

In general, if you are running a query in a loop, there is probably a better way of doing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top