我有一个非常简单的搜索页面,用于运行数据库中一个表的查询。我有查询和获取工作。但如果它没有找到用户输入的术语的任何匹配,那么我需要它说"没有返回的行#34;。
这是我的PHP代码:
<?php
include('./includes/dbConnection.php');
$result = null;
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
}
?>
以下是显示结果和错误的PHP:
<?php
if ($result != null) {
if (!empty($result)) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
}
} else {
echo "No Results";
}
?>
是否有更好的方式来显示&#34;没有返回结果&#34;?现在它只是在刷新时显示该错误,因为$ result确实等于null。
感谢您的帮助!
答案 0 :(得分:2)
删除$result = null;
,不需要它。您可以查看num_rows
返回您的查询。
<?php
include('./includes/dbConnection.php');
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
$_GET['pallet_id'] = addslashes($_GET['pallet_id']);
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
} else {
echo "No Results Returned";
}
}
?>