我试图弄清楚如何在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>
答案 0 :(得分:3)
也许这样对您有用。
将这些行替换为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;
}
}
答案 1 :(得分:1)
尝试一下:
$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;
}
}
答案 2 :(得分:0)
上面的答案很好,但是有人提供了完美的解决方案:
$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。它很干净,使您能够在无限制的包装器中发布无限制的内容,并且可以防止代码重复。谢谢吉姆。