sql 查询在使用 COUNT 时返回字符串而不是整数


sql query returning string instead of integer while using COUNT

$query_products_records="SELECT @MyInt=COUNT(*) FROM products";
$result_query_products_records=mysql_query($query_products_records);
echo 'table records ...'.$result_query_products_records;

使用上面的查询来获取表中的行数,但是我得到了

Resource id #4回声。

我在表中有 3 条记录。

mysql_query创建一个资源。

该资源应与 mysql_fetch_row() 一起使用。

mysql_fetch_row(mysql_query($query));

例如。或者在 while 循环中使用它来提取多个结果。

PS:还可以考虑在mysql上使用mysqli扩展。它已弃用。

工作代码

$result_data = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) as c FROM products"));
echo 'table records ...'. $result_data['c'];

没有获取结果集。 您正在使用回显mysql_query()因此Resource id #4输出。 使用 mysql_fetch_assoc()mysql_fetch_array() 获取结果集,然后对其进行回显。

$res = mysql_fetch_assoc($result_query_products_records);
// then echo as per required

这样做 -

$mysqli = new mysqli('host', 'username', 'password', 'database');//connection
$qry = "SELECT COUNT(*) AS total FROM products";
$result = mysqli_query($mysqli, $qry);//execute query
$res = mysqli_fetch_assoc($result);//fetch data
echo $res['total'];

改用以下代码

$query_products_records="SELECT anyFieldNeedInYourTable FROM products";
 $records=mysql_query($query_products_records);
 $result_query_products_records=mysql_num_rows(); 
echo 'table records ...'.$result_query_products_records;

并且不要忘记用真正的替换anyFieldNeedInYourTable。并考虑搬入Mysqli