COUNT vs mysql_num_rows

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
llanitedave
Forum Commoner
Posts: 78
Joined: Thu Jan 15, 2004 11:24 am
Location: Las Vegas, NV.

COUNT vs mysql_num_rows

Post by llanitedave »

What I want to do is:

Code: Select all

<?php
$sql = "select count from myTable where myField > yourDate";
$result = mysql_query($sql);
?>
But I'm not sure how to reference the result.
If I change the query to:

Code: Select all

<?php
$sql = "select * from myTable where myField > yourDate";

?>
In that case I can use mysql_num_rows to get the equivalent of "Count".
But is that how I really want to do it? It seems that there should be a more direct way to get Count out of the database.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Try this:

Code: Select all

$sql = "SELECT COUNT(myField) FROM myTable WHERE myField > yourDate";
$result = mysql_query($sql);
$count = mysql_result($result, 0);
For just getting one result from the database [php_man]mysql_result[/php_man]() is quite handy.

Mac
User avatar
llanitedave
Forum Commoner
Posts: 78
Joined: Thu Jan 15, 2004 11:24 am
Location: Las Vegas, NV.

Post by llanitedave »

Thanks! The PHP manual put me off a bit from trying this when it mentioned that mysql_result is slower than using a command that takes entire rows at once. Maybe I misinterpreted the meaning of it, if I'm applying it to just a single piece of data.
Post Reply