[英]How do you echo content before the while loop?
我試圖弄清楚如何在while循環上方和num_rows檢查下回顯內容,但是在執行此操作之前,我需要從while循環中獲取內容。
$sql = "SELECT * FROM table WHERE column = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $test);
$result = $stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
echo "<div id='wrapper'>"; //I need to add HTML content here if $status === 2
while ($row = $stmt_result->fetch_assoc()) {
$title = $row['title'];
$description = $row['descript'];
$status = $row['status'];
if ($status === 2) {
echo $status;
continue; //skip to the next iteration
}
echo $title;
echo $description;
}
}
也許我錯過了顯而易見的事情。 怎么做?
總而言之,這是我正在尋找的輸出:
//if status !== 2: (i get 3 results)
<div id='wrapper'>
//title
//description
//title
//description
//title
//description
</div>
//if status === 2: (i get 1 result)
<div id='other_wrapper'>
//title
//description
</div>
//if status === 3: (i get 5 results)
<div id='yet_another_wrapper'>
//title
//description
//title
//description
//title
//description
//title
//description
//title
//description
</div>
也許這樣的事情可能對您有用。
將這些行替換為while循環
$rows = $stmt_result->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
if ($row['status'] === 2) {
$title = $row['title'];
$description = $row['descript'];
$status = $row['status'];
if ($status === 2) {
echo $status;
continue; //skip to the next iteration
}
echo $title;
echo $description;
}
}
嘗試這個:
$idv =0;
if ($stmt_result->num_rows > 0) {
while ($row = $stmt_result->fetch_assoc()) {
if($row['status'] ==2 && $idv==0){
$idv =1;
echo "<div id='wrapper'>"; //adds div once only if status is 2
}
$title = $row['title'];
$description = $row['descript'];
$status = $row['status'];
if ($status === 2) {
echo $status;
continue; //skip to the next iteration
}
echo $title;
echo $description;
}
}
上面的答案很好,但是有人提供了完美的解決方案:
$wrappers = [
'wrapper' => [/* items from db with status not 2 or 3 */]
'other_wrapper' => [/* items from db with status 2 */]
'yet_another_wrapper' => [/* items from db with status 3 */]
];
function getWrapperNameForStatus($status) {
if($status === 2) {
return 'other_wrapper';
}
if($status === 3) {
return 'yet_another_wrapper';
}
return 'wrapper';
}
$wrappers = [];
while ($row = $stmt_result->fetch_assoc()) {
$wrapperName = getWrapperNameForStatus($row['status']);
$wrappers[$wrapperName][] = [
'title' => $row['title'],
'description' => $row['description'],
'status' => $row['status']
];
}
有關此解決方案, 請訪問https://www.phphelp.com/u/JimL 。 它很干凈,使您能夠在無限制的包裝器中發布無限制的內容,並且可以防止代碼重復。 謝謝吉姆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.