不久前将我的普通 SQL 查询转换为准备好的语句,但现在我想实现一个函数,但我不确定如何实现。以下是我当前的代码:
$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)
}
一切正常,没有任何问题。但是,对于某些页面,我想打乱结果的前 20 行(仅前 20 行!)。感谢其他人的帮助,我了解到最好的方法是将结果放入查询中并执行以下操作:
$first20 = array_splice($allResults,0,20);
shuffle($first20);
array_splice($allResults,0,0,$first20);
但是,我不确定如何将结果放入数组中?我应该能够在 while 循环($stmt->fetch)中做到这一点,但不确定如何做?一旦结果在一个数组中,我可以用上面的代码将它切片,放回数组中并以新的顺序显示结果。如何在数组中插入行?
答案是(完整的代码):
$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 />";
}
最佳答案
我会做的是像你说的那样把它全部放入一个数组中然后回显出来。
$array = array();
while($stmt->fetch()) {
$array[] = array('prepid'=>$prepid, 'prephoofdrubriek'=>$prephoofdrubriek, 'prepplaats'=>$prepplaats, 'prepbedrijfsnaam'=>$prepbedrijfsnaam);
}
我只在数组中放了几个来演示如何做。
然后为了获取数据,我会使用 for 循环。
$cnt = 20; // if you wanted to get them all you could set it to $cnt = array_count($array);
foreach ($i = 0; $i <= $cnt; $i++) {
echo $array[$i]['prepid'];
}
关于php - 查询中的准备语句结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23654351/