我正在尝试使用 PDO 从 mysql 获取数据并将其输出到 html 表中,如下所示
<div class="data">
<table class="table table-striped">
<?php
if($_POST['submit'] && $_POST['search_for'] == "keyword") {
$stmt = $db->prepare("SELECT * FROM my_tbl WHERE log like '%?%' ORDER BY submission_timestamp DESC");
foreach($stmt->execute($_POST['search_for']) as $row):
} elseif($_POST['submit'] && $_POST['search_for'] == "address") {
$stmt = $db->prepare("SELECT * FROM my_tbl WHERE address like '?' ORDER BY submission_timestamp DESC");
foreach($stmt->execute($_POST['search_for']) as $row):
} else {
foreach($db->query('SELECT * FROM my_tbl ORDER BY submission_timestamp DESC') as $row):
}
?>
<tr>
<td width="10%"><?php echo $row['address'] ?></td>
<td><?php echo $row['log'] ?></td>
<td width="10%"><?php echo $row['submission_timestamp'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
我在 elseif 声明之前出现了意外的“}”错误。
虽然当我使用时
<div class="data">
<table class="table table-striped">
<?php
foreach($db->query('SELECT * FROM my_tbl ORDER BY submission_timestamp DESC') as $row):
?>
<tr>
<td width="10%"><?php echo $row['address'] ?></td>
<td><?php echo $row['log'] ?></td>
<td width="10%"><?php echo $row['submission_timestamp'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
没有发生错误,代码正常工作,从 mysql 数据库中获取数据并将其显示为 html 表。
我本质上想根据发送到页面的发布数据更改表的输出。
有没有一种方法可以使用与后面类似的 if 语句格式化第一个代码,或者我应该在每个 if 语句循环时回显 html (我假设发生错误是因为它正在关闭 foreach 子句或其他什么)。
最佳答案
<div class="data">
<table class="table table-striped">
<?php
if($_POST['submit'] && $_POST['search_for'] == "keyword") {
$stmt = $db->prepare("SELECT * FROM my_tbl WHERE log like '%?%' ORDER BY submission_timestamp DESC");
$rows = $stmt->execute($_POST['search_for'];
} elseif($_POST['submit'] && $_POST['search_for'] == "address") {
$stmt = $db->prepare("SELECT * FROM my_tbl WHERE address like '?' ORDER BY submission_timestamp DESC");
$rows = $stmt->execute($_POST['search_for'];
} else {
$rows = $db->query('SELECT * FROM my_tbl ORDER BY submission_timestamp DESC') ;
}
foreach($rows as $row):
?>
<tr>
<td width="10%"><?php echo $row['address'] ?></td>
<td><?php echo $row['log'] ?></td>
<td width="10%"><?php echo $row['submission_timestamp'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
关于php foreach 与嵌入的 html 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21519497/