John
John

Reputation:

If statement not working

I want the output of the code below to be "$entry does not exist" if there is no $entry value anywhere under the "site" column in the database. However, this is not happening when I enter in a value for $entry that I know is not under the "site" column in the database. Is there something wrong with my if statement?

Thanks in advance,

John

$result = mysql_query("SHOW TABLES FROM feather") 
or die(mysql_error()); 


while(list($table)= mysql_fetch_row($result))
{
  $sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";

  $resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
  if(mysql_num_fields($resA)>0){
  list($isThere) = mysql_fetch_row($resA);
  if ($isThere)
  {
     $table_list[] = $table;
  }
  }
  else{
print "<p class=\"topic\">$entry does not exist</p>\n";
}
}

Upvotes: 0

Views: 193

Answers (2)

Paul Tarjan
Paul Tarjan

Reputation: 50602

Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Upvotes: 0

razzed
razzed

Reputation: 2683

Yes. Your formatting doesn't really do it justice, though, try and clean it up so it's easier to understand. NetBeans IDE, or even Zend Development Environmont ($) do automatic code formatting, and it make life a lot easier.

$result = mysql_query("SHOW TABLES FROM feather") or die(mysql_error()); 
while(list($table)= mysql_fetch_row($result)) {
    $sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";

    $resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
    if(mysql_num_fields($resA)>0){
        list($isThere) = mysql_fetch_row($resA);
        if ($isThere) {
            $table_list[] = $table;
        }
    } else{
        print "<p class=\"topic\">$entry does not exist</p>\n";
    }
}

In short:

mysql_num_fields($resA) is ALWAYS greater than zero, because the COUNT(*) function will always return a value, regardless (0 or 1 or 1000000, etc.)

To fix, put the else one level up, and I would use coercion to be safer. Finally, the mysql_num_fields isn't really necessary, because you know it's always 1:

$result = mysql_query("SHOW TABLES FROM feather") or die(mysql_error()); 
while(list($table)= mysql_fetch_row($result)) {
    $sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";
    $resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
    list($isThere) = mysql_fetch_row($resA);
    $isThere = intval($isThere);
    if ($isThere > 0) {
        $table_list[] = $table;
    } else{
        print "<p class=\"topic\">$entry does not exist</p>\n";
    }
}

And there you have it.

Upvotes: 4

Related Questions