tags:

views:

39

answers:

3

Hi guys, I have this code, but strangely it always echos out "yes!", even if there is no such value as '555' in FLD2 or even if there's no FLD2 at all.

$testresult = mysqli_query($database, "SELECT * FROM imei359327039828680 WHERE FLD2 = '555'");

if ( $testresult ) { echo('yes!'); } else { echo('no!'); }

Any idea, thanks!

+1  A: 

mysqli_query always returns a result object unless the query fails somehow. If the query just doesn't return any rows, you still get a result object; it just won't have any rows in it.

Syntactic
THNAKS, now it works!$testresult = mysqli_query($database, "SELECT * FROM imei359327039828680 WHERE FLD2 = '555'");$testrow = mysqli_fetch_array($testresult);if ( $testrow ) { echo('yes!'); } else { echo('no!'); }
+1  A: 

You're testing if $testresult is true, not if their are the expected results of the query. If the query is valid, i.e. well formed, it will return a valid object. You want to look into the $testresult return value to see if you found something or not.

ctshryock
+1  A: 

As was mentioned by ctshryock, a variable set to the returned value of a well-formed SQL query will always be seen as true when reviewed as a boolean object.

To test whether any data was returned, you could use mysql_num_rows()PHP Documentation which will return the number of rows returned. If your query would not match any rows, then this function should return 0 which would be seen as false by an if() condition.

$testresult = mysql_query( "SELECT * FROM imei359327039828680 WHERE FLD2 = '555'" );

if( !$testresult )
  die( 'SQL Error' ); # The SQL Query Failed for some reason

if( mysql_num_rows( $testresult ) )
  die( 'SQL Returned No Result' ); # The SQL Query returned nothing

while( $r = mysql_fetch_assoc( $testresult ) ) {
  # Process your returned rows here
}
Lucanos