Re: $result = mysql_query($query);

From: Date: Sat, 14 Sep 2002 20:27:54 +0000
Subject: Re: $result = mysql_query($query);
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-116401@lists.php.net to get a copy of this message
I'm not sure where exactly you read this, but I *think* you are confusing two different methods of doing basically the same thing. If all you want to do is determine the number of rows in a result set, selecting count(*) is more appropriate, and you use the same where clause you would use otherwise. This is the quickest way to get this information. However, if you are going to conditionally want to do something with the result set, you want to select whatever you need and do a mysql_num_rows() on that. Otherwise, you might have to execute an additional query, which is a waste. Let me try to explain this with an example. Say you want to find out how many employees took a vacation day. You might use a query like this: select count(*) as num_employees from employees where vacation_days_taken > '0' You can then use the num_employees field to print the number. Since this is all the information you want to print, it's the best approach. If you want to print the names of employees who took a vacation day, you want to go ahead and obtain that information within one query: select employee_name from employees where vacation_days_taken > '0' Using this method, your logic would then use mysql_num_rows() on the result of this query to determine whether there are any names to be printed (maybe you want to print "None found" rather than leave the section blank). If there are, you just print the names rather than executing another query. A similar method would be to explicitly select the count as well: select employee_name, count(*) as num_employees from employees where vacation_days_taken > '0' Most importantly, if you perform a mysql_num_rows() on a result of a query for select count(*), you're always going to get 1. This is a common pitfall worth avoiding, and it's what it sounded like you were lead to believe. Happy hacking. Chris Daniel Gosselin wrote:
I read on php.net that you have to use SELECT count(*) with if(mysql_num_rows($result) != 0) but if i use count(*) and i have no result to show the tile is printed with empty result so i'll use if($row = mysql_fetch_array($result)), work fine,


« previous php.general (#116401) next »