I use the following function to do this...

function countRecords($query, $dbcon=0) {
    if ($dbcon==0) { $ dbcon = connDbase(); }
    $query = "SELECT COUNT(*) ".$query;
    $res = mysql_query($query, $ dbcon);  // Query DB.
    return mysql_result($res, 0, "count(*)");

Here's how it's used:

$count = countRecords("FROM mydb WHERE id = 1001");

All I have to do is provide the query starting with FROM as the function
creates the SELECT COUNT(*) part. Also, the optional second parameter is to
pass the database connection resource ID to the function if I've already
established one before calling this function. This prevents the function
from having to establish a second DB connection for the count. If the second
param is left empty then a DB connection will be made using another
function: connDbase().

$count will contain the number of records that match the query and only
requires me to type one line of code.


> From: [EMAIL PROTECTED] (James Taylor)
> Newsgroups: php.general
> Date: Sat, 26 Oct 2002 03:23:23 -0700
> Subject: mysql_fetch_row options
> There's got to be a better way to go about this: I am constantly doing mysql
> queries where I am doing
> a count(), so a sample query would be like this: "select count(*) from
> database".  I'm expecting only
> ONE value back exactly, and that's the count results.  However, to get this
> data into a variable, i'm
> having to write code like this:
> $result = mysql_query("select count(*) from database", $db);
> $myrow = mysql_fetch_row($result);
> $staticvar += $myrow[0];
> $staticvar will never be an array, it's just a simple variable storing a
> number.  I *could* do it like this:
> $result = mysql_query("select * from database", $db);
> $staticvar += mysql_num_rows($result);
> However, the mysql query will be much, much slower if I do it like this.
> Basically, what I'm asking, is how to do something like:
> $staticvar += mysql_fetch_row($result);
> I want to eliminate step two, and I don't want to involve any temporary
> arrays when there's always just one
> value.  Any suggestions? Thanks a bunch!

PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to