themerlinproject
themerlinproject

Reputation: 3582

More efficient way to COUNT() MYSQL rows via PHP?

Here is how I am currently counting mysql rows in PHP:

//GET total # of results and build $start and $end for main SQL statement
$sql= 'SELECT COUNT(*) FROM savedsearches WHERE user_id=\''.mysql_real_escape_string($user_id).'\'';
$initial_query = mysql_query($sql) or die("SQL error");
$num_sql = mysql_fetch_array($initial_query);
$numrows = $num_sql[0];
mysql_free_result($initial_query);

Is there a more efficient way to do this?

Upvotes: 3

Views: 7858

Answers (3)

Omar Juvera
Omar Juvera

Reputation: 12287

//GET total # of results and build $start and $end for main SQL statement
$sql= 'SELECT * FROM savedsearches WHERE user_id=\''.mysql_real_escape_string($user_id).'\'';
$initial_query = mysql_query($sql) or die("SQL error");
$numrows = mysql_num_rows($initial_query)

As you can see, you can run mysql_num_rows() BEFORE mysql_fetch_array. This is very useful to me, since it allows me to know before hand, weather or not I have the amount of rows I need. If you want to learn more about this function: PHP Manual: mysql_num_rows()

Upvotes: 0

nos
nos

Reputation: 229058

No. If you want a count , you run the query you're already running.

If you need more efficiency, make sure there is an index on the user_id column

Upvotes: 3

Hammerite
Hammerite

Reputation: 22340

You mean, do it in fewer lines of code? You could put that functionality into a user-defined function and then call the function instead of using that code, but other than that, it's not going to get an awful lot terser.

Upvotes: -1

Related Questions