如果没有结果而不是所有时间,我怎样才能显示无结果语句?

时间:2015-11-22 23:45:36

标签: php mysqli

我设置的while / if / else语句的工作原理除了无结果消息显示的事实,无论是否返回resuts。我试过设置"休息"声明所以它允许循环适当地退出,但我不能在正确的位置得到它。

<html>

<head>

</head>

<body>

<p>Search the Customer Database</p>

<form action="Index.php" method="post">
  <input type="text" name="search" placeholder="Search...." />
  <input type="submit" value=">>" />
</form>

<?php

$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}


// If there is a search variable try to search database
if(isset($_POST['search'])) {
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
    $sql = "SELECT * FROM Customers WHERE Client LIKE '%$searchq%'";

        if ($result = mysqli_query($conn, $sql)) {

/* fetch associative array */
    while (true)

if ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)<br/>", $row[0], $row[1]);    }

else {printf ("There were no Results");
 break;    



    /* free result set */
    mysqli_free_result($result);
}
}

/* close connection */
mysqli_close($conn);
}

?>

</body>

</html>

1 个答案:

答案 0 :(得分:1)

另一种解决方案是在尝试获取查询之前检查查询返回的行数。这样,您在进入if ($result = mysqli_query($conn, $sql)) { if (mysqli_num_rows($result) > 0) { // We have results! Go fetch rows! while ($row = mysqli_fetch_row($result)) { // This loop runs until there are no more results left to echo printf ("%s (%s)<br/>", $row[0], $row[1]); } } else { // No results from query printf ("There were no Results"); } /* free result set */ mysqli_free_result($result); } 循环之前检查实际是否获得了一些结果,如果您没有(意味着没有结果),则会相应地显示一条消息。

{{1}}