简体   繁体   中英

mysql_num_rows give unexpected result

I've got the following function:

public function already_tweeted($tweet){
        return mysql_num_rows(mysql_query("SELECT * FROM `retweeted` WHERE `tweet`='$tweet'"));
    }

Pretty straightforward. It checks whether a tweet already exists in the database.

The table had the following records:

id  user    tweet
3       You should retweet this too
2       Retweet this

(user is empty for now)

This code:

$db_reader = new database_reader;
$already_tweeted = $db_reader->already_tweeted($tweet);
print $tweet . ". Already: ";
var_dump((bool) $already_tweeted);
print "<br>";

Gives the following output:

You should retweet this too. Already: bool(false) 
Retweet this. Already: bool(true) 

I'm pretty much stuck here. When I run SELECT * FROM retweeted WHERE tweet ='You should retweet this too' in phpmyadmin I get 1 row back.

Check what is the value in $tweet

similar problem

Also change this line to be safe

return mysql_num_rows(mysql_query("SELECT * FROM retweeted WHERE tweet ='{$tweet}'"));

return mysql_num_rows(mysql_query("blah-blah")); is a dirtiest way to run a query.
make a helper function instead of this horror.

mysql_num_rows() is a dirtiest way to count rows, SELECT count(*) wuery should be used instead.

//put this function to your function library
function dbgetvar($query){
  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return FALSE;
  }
  $row = mysql_fetch_row($res);
  if (!$row) return NULL;
  return $row[0];
}
public function already_tweeted($tweet){
  $tweet = mysql_real_escape_string($tweet);
  return dbgetvar("SELECT count(*) FROM `retweeted` WHERE `tweet`='$tweet'"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM