S.e. Estes
S.e. Estes

Reputation: 75

PHP, MYSQL - Query fails but no error meessage appears

Back again, thanks for all the help last time. I'm running this query:

 $query = "SELECT * FROM event where evLoc = ".$loc." AND evChar = ".$char;
 var_dump($query);
 $result = mysql_query($query, $con) or die('Error 1:'.mysql_error());
 if ($result) {
    $row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
    var_dump(mysql_num_rows($result));
    exit();

I get a message Error 2: but no mysql_error printed out. The var_dump($query) printed out a query that ran without errors in phpMyAdmin. The var_dump(mysql_num_rows($result)) did not print.

Upvotes: 2

Views: 2233

Answers (3)

Starx
Starx

Reputation: 79069

Apply Single Quotes in the fields of your query

 $query = "SELECT * FROM event where evLoc = '".$loc."' AND evChar = '".$char."'";

You can write these in short form too. Like

$query = "SELECT * FROM event where evLoc = '$loc' AND evChar = '$char'";

Next, you might want to change your fetch portion.

while($row = mysql_fetch_assoc($result)) { 
 ....
}

When you use this, you will avoid the error you would receive when no rows are returned.

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270775

This is a case of being too cautious and applying error checking where it doesn't belong.

Don't call die() in partnership with a fetch call. The fetch intentionally returns FALSE when there are no rows available, so you don't have an error, just no rows.

// No rows were returned, wich is FALSE
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());

Instead, don't call die() here:

$row = mysql_fetch_array($result);
if ($row) {
  // you got something
}

Or this way:

if ($row = mysql_fetch_array($result)) {
  // you got something.
}

If multiple rows are expected to be returned, fetch in a while loop.

while ($row = mysql_fetch_array($result)) {
  // loops until you're out of rows
  // or not at all if you have no rows
}

Upvotes: 2

heximal
heximal

Reputation: 10517

Obviously, your request returns 0 rows and mysql_fetch_array returns FALSE

Upvotes: 2

Related Questions