我有一个声明,非常基本的,从数据库中提取并显示信息。有用。但是,如果我删除数据库中的条目,则else语句应该说没有结果。但事实并非如此。有谁能看到这个问题?
这是代码,我正在考虑的是if($ result){
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else {
$result = mysqli_query($con,"SELECT * FROM vacancies WHERE status ='0'");
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "<li><a href=\"current_vacancy?id=".$row['id']. "\">". $row['title'] ."</a> <img src=\"rightarrow.png\" alt=\"next\"></li>";
}
} else {
// execute for 0 rows returned.
echo "There are currently no vacancies available";
}
}
由于
答案 0 :(得分:2)
如果SELECT
操作成功,则mysqli_query()
将始终返回对象。无论该对象保存0个或多个记录,它始终为true。相反,您应该做的是从结果中获取所有记录。
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli("localhost", "user", "pass", "db");
$con->set_charset('utf8mb4'); // always set the charset
$result = $con->query("SELECT * FROM vacancies WHERE status ='0'");
$data = $result->fetch_all(MYSQLI_BOTH);
if ($data) {
foreach ($data as $row) {
echo "<li><a href=\"current_vacancy?id=".$row['id']. "\">". $row['title'] ."</a> <img src=\"rightarrow.png\" alt=\"next\"></li>";
}
} else {
// execute for 0 rows returned.
echo "There are currently no vacancies available";
}
答案 1 :(得分:1)
要实现无结果,您需要通过查询mysqli_num_rows()
来检查您获取的行数。
在您的情况下,您检查了$ result变量,这将存储查询执行的状态,因此它将始终为true,因为即使查询没有返回任何行,查询也将始终执行。
答案 2 :(得分:0)
mysqli_query
返回的结果是一个对象,而不是行数。使用mysqli_num_rows($result)
获取行数。
顺便说一句,请务必在结尾处致电mysqli_free_result($result)
。建议大纲:
$result = mysqli_query(…);
if (!$result) {
# Handle failure
} else {
if (mysqli_num_rows($result) == 0) {
# Handle no vacancies
} else {
# Normal case
}
mysqli_free_result($result);
}
答案 3 :(得分:0)
使其更自然
$data = [];
$result = $con->query("SELECT * FROM vacancies WHERE status ='0'");
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
?>
现在您可以按照尝试使用$ result的方式使用$data
:
<?php foreach ($data as $row): ?>
<li>
<a href="current_vacancy?id=<?=$row['id']?>">
<?=$row['title']?>
</a>
<img src="/images/rightarrow.png" alt="next">
</li>
<?php endforeach ?>
<?php if(!$result): ?>
There are currently no vacancies available
<? endif ?>