0

The while/if/else statement I set up works except for the fact that the no results message shows up regardless of whether resuts are returned or not. I've tried setting the "break" statement so it allows the loop to exit appropriately, but I can't get it in the right spot.

<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>
Tony
  • 298
  • 3
  • 17

1 Answers1

1

A different solution would be to check how many rows was returned from the query before trying to fetch them. This way, you check that you actually get some results before you enter the while-loop, and if you don't (meaning there were no results), you display a message accordingly.

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);
}
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • I appreciate the help. I didn't know I could nest the if/while/else as you did. I found several examples of while/if/else and went with that. I did see a few places that discussed checking the rows first but the code I tried using didn't generate resuts. I knew I was close with what I asked here though. Thanks again for all of the help. – Tony Nov 23 '15 at 00:12
  • Happy to help! Generally using `while(true)` isn't very good practice ;) However, I'd also advise you to take a look at [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Glad you fixed your problem, though! :) – Qirel Nov 23 '15 at 00:16