显示"未找到结果"用PHP

时间:2014-09-15 06:32:42

标签: php mysql mysqli

美好的一天! 我无法显示"未找到任何记录"我的PHP过程中的消息 以下是我的搜索查询的代码:

if(isset($_GET['submit'])) {

$product = $_GET['product'];
$city = $_GET['city'];

$query = "SELECT * FROM $product WHERE city = '$city'";
$result = mysqli_query($con, $query) or die ("Could not connect to database.");
$product = str_replace('_', ' ', $product);
$product = strtoupper($product);
   echo "You have searched for " . $product . " in " . $city;
   echo "<table border=1>";
   echo "<tr> <th>Store</th> <th>City</th> </tr>";
    while ($row = mysqli_fetch_array($result)) {
     echo "<tr><td>";
     echo $row['store'];
     echo "</td><td>";
     echo $row['city'];
     echo "</td></tr>";
    }
     echo "</table>";
}

我的问题是我不知道在哪里放置条件语句会显示什么,以及#34;没有找到记录&#34;。
希望有人能够帮助我解决这个问题 提前谢谢。

3 个答案:

答案 0 :(得分:2)

通过mysqli_num_rows函数检查结果中的行数是否为0,并在循环结果集之前显示消息。

您的代码可能就像

if(isset($_GET['submit'])) {

    $product = $_GET['product'];
    $city = $_GET['city'];

    $query = "SELECT * FROM $product WHERE city = '$city'";
    $result = mysqli_query($con, $query) or die ("Could not connect to database.");
    $product = str_replace('_', ' ', $product);
    $product = strtoupper($product);
    echo "You have searched for " . $product . " in " . $city;
    echo "<table border=1>";
    // check if results are present
    if(mysqli_num_rows($result)>0) {
        echo "<tr> <th>Store</th> <th>City</th> </tr>";
        while ($row = mysqli_fetch_array($result)) {
             echo "<tr><td>";
             echo $row['store'];
             echo "</td><td>";
             echo $row['city'];
             echo "</td></tr>";
        }
    } else {
        echo "<tr> <td colspan='2'> No Results found </td></tr>";
    }
     echo "</table>";
}

答案 1 :(得分:0)

mysqli_affected_rows()函数返回上一个SELECT,INSERT,UPDATE,REPLACE或DELETE查询中受影响的行数。

来自参考资料:http://php.net/manual/tr/mysqli.affected-rows.php

大于零的整数表示受影响或检索的行数。零表示没有为UPDATE语句更新记录,没有与查询中的WHERE子句匹配的行或者尚未执行任何查询。 -1表示查询返回错误。

    $product = $_GET['product'];
    $city = $_GET['city'];

    $query = "SELECT * FROM $product WHERE city = '$city'";
    $result = mysqli_query($con, $query) or die ("Could not connect to database.");
    $product = str_replace('_', ' ', $product);
    $product = strtoupper($product);
       echo "You have searched for " . $product . " in " . $city;    

    if(mysqli_affected_rows($con) ==0){ echo  "No records found"; }

    else{
       echo "<table border=1>";
       echo "<tr> <th>Store</th> <th>City</th> </tr>";
       while ($row = mysqli_fetch_array($result)) {
         echo "<tr><td>";
         echo $row['store'];
         echo "</td><td>";
         echo $row['city'];
         echo "</td></tr>";
        }
         echo "</table>";
    }

答案 2 :(得分:0)

您应该尝试使用此代码,如果您的代码中的任何代码有任何错误,那么您可以找到它。

$result = mysqli_query($con, $query) or die(mysqli_error($con));

OR
if(!$result){
echo die(mysqli_error($result));
}