user1686689
user1686689

Reputation: 23

Error message in PHP when there's no data via MYSQL?

I've got a php file fetching some data from a MYSQL database. This is my code so far:

<?php
    include 'DB.php';
    $connection=mysql_connect(DB_SERVER,DB_USER,PASS);
    $db=mysql_select_db(DB_Name);
    $sql="select * from lookup where id = ".$_GET['id'];
    $res=mysql_query($sql) or die(mysql_error());
    while($row=mysql_fetch_array($res))
        {
        echo $row['message'];
        }
?>

What would I have to add so that if there was no data, there'd be an error message? I'm guessing an If/else statement but I'm not sure how to fit it in with the while syntax.. any help?

Upvotes: 0

Views: 132

Answers (3)

Randy
Randy

Reputation: 31

I did it like mentioned above:

$query = "select * from lookup where id = ".$_GET['id'];
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 0){
echo "nothing here</br>";
}
else{
echo "<b> $num_results </b> result(s) match your query</br>";
while($row=mysql_fetch_array($res))
    {
    echo $row['message'];
    }

You can of course leave the "echo $num_results..." out, but there you can give the number of results, which is sometimes quite useful.

Upvotes: 0

alanmanderson
alanmanderson

Reputation: 8210

You can use $count = mysql_num_rows($res); to get the number of rows returend. Then you can use an if statement to display whatever error.

Upvotes: 0

Marc B
Marc B

Reputation: 360702

$res = mysql_query(...) ...;
if (mysql_num_rows($res) == 0) {
   die("Hey, nothing here!");
}

Beyond that:

a) you're utterly vulnerable to SQL injection attacks. Stop your coding project and learn about them before you go any further.

b) stop using the mysql_*() functions. They're deprecated.

Upvotes: 1

Related Questions