views:

60

answers:

1

Hello guys I'm stucked at this point. So I need your help, thanks anyway.

I'm using this code to count rows and trying to do IF num rows equals to ZERO do INSERT if not UPDATE but doesnt works. When I use "==" operator nothing happens, if I use ">=" operator script inserting the values but running insert query on every refresh and values are duplicating in mysql table. here is the code, whats wrong with this thing? thank you.

$isexist = mysql_query("select count(*) from wcddl_filehosts where downloadid = '".$download[id]."'");

if (mysql_num_rows($isexist) == 0) {
mysql_query("insert into wcddl_filehosts (downloadid, rs) values ('".$download[id]."','$totalRS')");
} else {
mysql_query("update wcddl_filehosts set rs = '$totalRS' where downloadid = '".$download[id]."'");
}
+7  A: 

Count will return a value, and you cannot count and then call mysql_num_rows. It is either one of the other.

You could do

$isExist = mysql_query("Select count(id) from ..."); 
$r = mysql_fetch_array($isExist);
if($r['COUNT(id)'] > 0){
//item exists
}else{
//item doesnt exist
}

If alternatively you can do the query as:

$isexist = mysql_query("select * from wcddl_filehosts where downloadid = '".$download[id]."'");
if(mysql_num_rows($isExists)>0){
//we have items
}else{
//we dont have items
}
Chris
thank you very much for your answer. but i want to ask which way faster?
Ronnie Chester Lynwood
It is a matter of mysql returning the count itself versus php performing the count. I would imagine MySQL is better at counting then php is however this is just a hunch, nothing more nothing less. :-) Although if you are talking about millions of records then MySQL will be faster I am almost positive.
Chris
The reason using MySQL to count is a better choice is because MySQL doesn't have to build and send back the entire result set (which in the case of millions of records is a LOT Of data) before a total is calculated. The general rule of thumb when you're using SELECT from MySQL is never to return results you don't need, as it's a waste of I/O resources.
AvatarKava