如何将SQL COUNT语句的结果存储在PHP变量中

问题描述:

我想获取MySQL表中的行数并将其存储在php变量中.这是我正在使用的代码:

I want to get the number of rows in my MySQL table and store that number in a php variable. This is the code I'm using:

$size = @mysql_query("SELECT COUNT(*) FROM News");

$ size最终是资源ID#7".如何将行数直接放入$ size?

$size ends up being "Resource ID #7." How do I put the number of rows directly into $size?

mysql_query返回查询资源ID.为了从中获取值,您需要在资源ID上使用mysql_fetch_assoc,以将行读取到数组中.

mysql_query returns a query resource id. In order to get values from it you need to use mysql_fetch_assoc on the resource id to fetch a row into an array.

$result = mysql_query("SELECT COUNT(*) FROM News");
$row = mysql_fetch_assoc($result);
$size = $row['COUNT(*)'];