开发者

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 sa开发者_运维百科vedsearches 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?


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


//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()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜