1

How do I return an error from the following query if there is no email address found in the database that corresponds to the variable $check_email. As it stands I can put any gobbledygook into the textfield on my site and it still retrieves a $result. (Have escaped the string. Moving onto prepared statements in time so bear with me on that point).

I hoped to have the error message that you see here.

$query  = "SELECT lastimage FROM scorers WHERE email = '{$check_email}'";
$result = mysqli_query($con, $query);

// Test if there was a query error
if (!$result) 
{
    die("We cannot find you in the database, please start again!");
}
while($row = mysqli_fetch_row($result)) 
{
    // output data from each row
    $image_number= $row[0];
}
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
GhostRider
  • 2,109
  • 7
  • 35
  • 53
  • **You are leaving yourself wide open to SQL injection attacks.** Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app. http://bobby-tables.com/php has examples to get you started, and [this question](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has many examples in detail. – Andy Lester Sep 07 '13 at 17:04
  • Cheers. I did however think I was fairly clear that I was aware of this and that I agree that ultimately prepared statements would be better. All things in time. I have used msqli_real_escape_string for all my variables which while not as good, is of some benefit. – GhostRider Sep 07 '13 at 18:00

2 Answers2

1
$sql = "select count(*) from scorers where email = '$email'";
$result = mysql_query($sql);
if($result > 0)
{
    die("We cannot find you in the database, please start again!");
}
Ankit Agrawal
  • 6,034
  • 6
  • 25
  • 49
0

$query  = "SELECT lastimage FROM scorers WHERE email = '{$check_email}'";
$sql = mysqli_query($con, $query);

// put the results into an array
$result = mysqli_fetch_assoc($sql);

// see if there was a result
if(count($result) > 0) {
    echo 'found';
} else {
    // don't use die(); handle your errors with an error handling function if you can
    $error_message = "We cannot find you in the database, please start again!";
}

Edit; Ankit Agrawal's answer is a better choice if you're not going to select additional data.

timgavin
  • 4,972
  • 4
  • 36
  • 48