如何使用PHP检索以下COUNT(*)MYSQL语句的结果?
MYSQL
$sql= mysql_query ("
select count(*)
from orders o
WHERE order_status IN
('Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order')
GROUP BY FIELD
(order_status,'Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order')
");
以上查询的结果
count(*)
226
19130
593
2603
2892
我已尝试使用以下代码按顺序检索每一行 -
PHP
$row = mysql_fetch_row($sql);
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
会产生以下错误:Notice: Undefined offset: 1 ...
我知道我遗漏了一些非常简单的东西,但有人请告诉我调用COUNT(*)查询结果的正确方法。
答案 0 :(得分:3)
您的查询返回5行。你必须循环它们并显示列:
while($row = mysql_fetch_row($sql)){
echo $row[0];
}
另请参阅documentation
使用计数的别名也是有意义的。
$sql= mysql_query = "
select count(*) as countValue
from orders o
WHERE order_status IN
('Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order')
GROUP BY FIELD
(order_status,'Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order')
";
while($row = mysql_fetch_row($sql)){
echo $row["countValue"];
}
警告:自PHP 5.5.0起,不推荐使用mysql_扩展名,将来会将其删除。相反,应该使用MySQLi或PDO_MySQL扩展。
答案 1 :(得分:2)
你需要添加循环来获取所有数据并使用mysqli而不是mysql。
类似这样的事情
$sql= "select count(*) as total from orders o WHERE order_status IN
('Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order') GROUP BY FIELD (order_status,'Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order')"
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
echo $row['total'];
echo "<br>";
}
您也可以使用与mysql相同的方法而不是mysqli,但mysqli将来会更好用。
$result = mysql_query($sql);
while($row = mysql_fetch_row($sql)){
echo $row['total'];
echo "<br>";
}
答案 2 :(得分:0)
$sql= mysql_query ("
select count(*) as nbre
from orders o
WHERE order_status IN
('Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order')
GROUP BY FIELD
(order_status,'Printed Order', 'Charged Order', 'Exchanged Order', 'Refunded Order', 'Cancelled Order')
");
echo $row[0]['nbre'];