Converted my normal SQL queries to prepared statements a while back, but now I want to implement a function and I'm not sure how. Below is my current code:
$stmt = $db->stmt_init();
$query = "pretty long query...";
$stmt->prepare($query);
$stmt->bind_param('ssii', $dienstenpage, $huidigegemeente, $startpoint, $limit);
$stmt->execute();
$stmt->bind_result($prepid, $prephoofdrubriek, $prepplaats, $prepbedrijfsnaam, $prepgemeente, $prepbedrijfsomschrijving, $prepbedrijfsslogan, $prepstraatnaam, $prephuisnummer, $preppostcode, $preptelefoonnummer, $prepfax, $prepemail, $prepwebsite, $prepbedrijfslogo, $prepdubb);
$stmt->store_result();
$numrows = $stmt->num_rows;
while($stmt->fetch()) {
Here appears a nice div with all the data for every result (row)
}
All works fine, no hick-ups there. However, for some of the page I want to shuffle the first 20 rows (only the first 20!) of the result. Thanks to the help of others I learned the best way to do that is to put the result in a query and do this:
$first20 = array_splice($allResults,0,20);
shuffle($first20);
array_splice($allResults,0,0,$first20);
However, I'm not sure how to put the results in array? I should be able to do that in the while loop ($stmt->fetch), but not sure how? Once the results are in an array I can slice it with the code above, put in back in the array and display the results in the new order. How do I insert the rows in an array?
THE ANSWER WAS (COMPLETED CODE):
$array = array();
while($stmt->fetch()) {
$array[] = array('prepid'=>$prepid, 'prephoofdrubriek'=>$prephoofdrubriek, 'prepplaats'=>$prepplaats, 'prepbedrijfsnaam'=>$prepbedrijfsnaam);
}
$first20 = array_splice($array,0,20);
shuffle($first20);
array_splice($array,0,0,$first20);
$number = count($array);
$cnt = $number; // if you wanted to get them all you could set it to $cnt = array_count($array);
for ($i=0; $i<=$cnt; $i++) {
echo $array[$i]['prepid'];
echo "<Br />";
}