我遇到了一个问题,我正在尝试查询一个表并获得一些结果,如果没有结果(空)那么它只是回显它是空的。
问题是,while($row = mysqli_fetch_assoc($result))
echo之前没有问题。但当它在while循环中时,它不会回复任何东西,甚至不回复if(mysqli_num_rows($result)==0)echo 'There is nothing';
或者如果我这样做
if(empty($result)){
echo "There is no";
以下是我的代码,感谢您的时间
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
include 'connect.php';
echo "It is working";
$Listingid = "648";
echo "$Listingid";
$result = mysqli_query($con,"SELECT * FROM list WHERE Listingid = '$Listingid'")
or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($result)) {
if(empty($result)) {
echo "There is no";
} else {
echo 'User ID:' . $row['userid'] . '<br>Username:' . $row['username'] . '<br>Useremail:' . $row['useremail'];
}
}
答案 0 :(得分:1)
试试这个逻辑
$sql = mysqli_query($con,"select count(*) as count from list WHERE Listingid = '$Listingid'");
while($row = mysqli_fetch_array($sql))
{
$count = $row['count'];
}
if($count == 0)
{
echo 'it is empty';
}
else
{
$result=mysqli_query($con,"SELECT * FROM list WHERE Listingid = '$Listingid'");
while($row = mysqli_fetch_array($result))
{
echo 'User ID:'.$row['userid'].'<br>Username:'.$row['username'].'<br>Useremail:'.$row['useremail'];
}
}
答案 1 :(得分:1)
试试这段代码:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
include 'connect.php';
echo "It is working";
$Listingid = "648";
echo "$Listingid";
$result = mysqli_query($con, "SELECT * FROM list WHERE Listingid = '$Listingid'");
if (mysqli_num_rows($result) == 0) {
echo "There is no";
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo 'User ID:' . $row['userid'] . '<br>Username:' . $row['username'] . '<br>Useremail:' . $row['useremail'];
}
}
?>
如果<{1}} - 循环之前有数据,则会检查,因为如果找不到任何结果,它将不会通过while
循环有了这个查询。
答案 2 :(得分:-1)
您是否尝试过使用mysqli_fetch_array();
代替mysqli_fetch_assoc();
?
mysqli_fetch_array();
获取所有字段,而mysqli_fetch_assoc();
返回包含行值的字段名称,而不是名称ex:
[0] => "Username", [1] =>"Email"
mysqli_fetch_array();
返回:
[0] => "username", [Username] => "username, [1] => "Email", [Email] => "Email"
和这部分:
if(empty($result)) {
echo "There is no";
}
是没用的,因为如果没有一行,那么循环就不会出现在脚本的这一点上。