Jump to content

checking if a value exist


amylisa

Recommended Posts

I'm trying to check if a value exists and then do something if it does and do something if it doesn't but with this code I get the returned number of rows as being 1 even when the value doesn't exist in the table. I've been googling for a while now and still cant work out what is wrong

 

$query = mysql_query("SELECT COUNT(*) FROM `names` WHERE username='".$username."'");
if (mysql_num_rows($query) > 0) { print "value exists"; }
else { print "value doesn't exist"; }

Link to comment
https://forums.phpfreaks.com/topic/162733-checking-if-a-value-exist/
Share on other sites

SELECT COUNT will always only ever return 1 row. You need to check that value in that row.

 

if ($query = mysql_query("SELECT COUNT(*) FROM `names` WHERE username='$username'")) {
  if (mysql_num_rows($query)) {
    if  (mysql_result($query,0) > 0) {
      print "value exists";
    } else {
      print "value doesn't exist";
    }
  }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.