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
- http://bytes.com/topic/php/answers/875805-mysql_num_rows-argument-not-being-recognized-any-help-would-appreciated
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'"));
}
精彩评论