0

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?

2

3 Answers 3

1
$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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'll look into the SQL injection article, thank you. And sorry.. could you give me the answer embedded in my current code? Real beginner here.. Thanks!
Best way to learn: figure out how to add that code to yours yourself. Because, frankly, this is a very very trivial addition. If you can't figure it out yourself, you definitely won't be up to tackling harder stuff later on.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.