0

I'M trying to output a message if the PHP query on the MySQL database come back empty. But when I uncomment this line //echo "No result found for entry"; not only does it fail to output this message when there is no match but it also fails to load the page at all. If this line is un commented I get nothing but a solid white page. PHP code is below. Any ideas?

<?php

// get variable from html form
$fName = $_POST['fname'];
$lName = $_POST['lname'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];

// Create connection
$con=mysqli_connect("localhost", "garrett", "xyz", "bailbond");

// Check connection
if(mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con, "SELECT * FROM people WHERE fname='$fName' or lname='$lName' or address='$address'");

if(!$result)
{
    //echo "MySQL Error: " . mysqli_error($con) . "\n";
    //echo "No result found for entry";
}

else
{
    while($row = mysqli_fetch_array($result))
    {
        echo $row['fname'] . " " . $row['lname'] . " " . $row['address'] . " " . $row['city'] . " " . $row['state'] . " " . $row['zip'];
        echo "<br /> <br />";
    }
}

?>
4
Contributors
3
Replies
22
Views
4 Years
Discussion Span
Last Post by Geffory
1

You're not checking for empty datasets, you're checking whether a resource is returned or not. So, $result will always be 'true' (i.e. a resource) as long as the query is valid and false otherwise.

It looks as though your query is run successfully, but it doesn't contain any rows.

To check do this:

if(!mysqli_num_rows($result))
{
    echo "No rows found for this entry";
}

Edited by diafol

1

you can do it something like this

$result = mysqli_query($con, "SELECT * FROM people WHERE fname='$fName' or lname='$lName' or address='$address'");
if(!$result)
{
echo "MySQL Error: " . mysqli_error($con) . "\n";
}

else
{
 if(mysqli_num_rows($result)==0)//to check if it is returns 0 rows affected
{
echo "No rows found for this entry";
}
else{
//do your stuff
}
}
1

You are not fetch the data into your SQL server. firstly, you have fetch the data into your database. you have to check localhost table name which are same in your coding format.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.