Here I want to pass the prepared statements as arguments of test function which should display the query results.But the code below doesn't work,because it may lack something that I don't know.What should I do in order to display results by the test function:
<?php
$mysqli = new mysqli("localhost","root","","test");
/*check connection*/
if(mysqli_connect_errno())
{
printf("connection failed: %s
",mysqli_connect_error());
exit();
}
/*create prapared statement*/
$stmt1 = $mysqli->prepare("select id from posts");
$stmt2 =$mysqli->prepare("select username from members where id=?");
$stmt1->execute();
$stmt1->store_result();
$stmt1->bind_result($ID);
/*bind params*/
$stmt2->bind_param('i',$id);
/*bind results*/
$stmt2->bind_result($username);
while($stmt1->fetch())
{
/*set params*/
$id =$ID;
/*execute prapared statement*/
$stmt2->execute();$stmt2->store_result();
}
test($stmt1,$stmt2);//function call
function test($stmt1,$stmt2)
{
while($stmt1->fetch())
{
while($stmt2->fetch())
{
echo 'Username: '.$username.'<br/>';
}
}
}
?>
I think this way could be not the lightweight solution but you can reset the result pointer with the mysqli_result::data_seek()
method and as you need again the result variable you have to rebind it:
function test($stmt1, $stmt2)
{
$stmt1->data_seek(0);
while($stmt1->fetch())
{
$stmt2->data_seek(0);
$stmt2->bind_result($username);
while($stmt2->fetch())
{
echo 'Username: '.$username.'<br/>';
}
}
}
test($stmt1, $stmt2);
An option could be to store in an array the binded results inside the while, and then use this array subsequently as many times as you want; However everything depends on your needs.
Source: http://www.php.net/manual/it/mysqli-result.data-seek.php
EDIT -------------------
I just suggested using an array to avoid reusing resource only for looping the same data.
Anyway, it may depends on your env but in case you have mysqlnd driver installed, you can do something like this:
$res1 = $stmt1->get_result(); // here you can use get_result() to get the resultset
$myAy = array();
while($row = $res1->fetch_array())
{
$myAy[] = $row;
}
var_dump($myAy);
or another way could be something like this:
...
$myAy = array();
while ($stmt1->fetch())
{
$id = $ID;
$myAy['id'] = $ID;
...
}
while ($stmt2->fetch())
{
$myAy['user'] = $username;
}
var_dump($myAy);
Just my two cents...