我有這樣一段代碼:遍歷MySQL查詢用PHP預處理語句和順序由INT
$item_number = 0;
$rowsize = 12;
for ($i = 0; $i < $rowsize; $i++) {
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, name FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE house_room1.ref_id = ? ORDER BY z');
$stmt->bind_param('i', $i
);
if ($stmt->execute()) {
$stmt->bind_result($z, $name);
while($stmt->fetch()) {
echo '<li id="item-' . $item_number . '" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $name . '</li>';
}
}
else {
echo 'Something went terribly wrong' . $mysqli->error;
}
$stmt->close();
//$n++;
$item_number++;
}
它通過一個查詢循環12次(目前12,將以更高),並選擇一個名稱和AZ來自特定ref_id的值。由於該循環經歷了12次,我從所有12個ref_id中獲得了z值。問題是我不能排序查詢,因爲它一次只取出一個查詢。嗯,我需要它得到所有12(及更多)的z值,並仍然能夠通過z值對輸出進行排序。最好只循環查詢一次。有任何想法嗎?提前致謝。
UPDATE:
$item_number = 0;
$i = 12;
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, name
FROM house_room1
INNER JOIN objects ON house_room1.object_id=objects.object_id
WHERE house_room1.ref_id < ?
ORDER BY z');
$stmt->bind_param('i', $i
);
if ($stmt->execute()) {
$stmt->bind_result($z, $name);
while($stmt->fetch()) {
echo '<li id="item-' . $item_number . '" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $name . '</li>';
}
}
else {
echo 'Something went terribly wrong' . $mysqli->error;
}
$stmt->close();
$item_number++;
是否有一個原因,你是限制到具體的ref ID的?你能包括你的表格列嗎?此外,你可以編輯你的問題,縮進不那麼嚴重? –
我試着用縮進大聲笑idc發生了什麼,呃我會在一秒內修復,ref_id的不受限制,可以通過時間增加。 – owwyess
任何時候你在循環內部都有一個查詢,某些事情就會消失「非常錯誤」 – Strawberry