我有这个问题:
$q = "SELECT SUM(cena) AS total, MONTH( datum ) AS mesec
FROM nakupi
GROUP BY mesec";
$po = $mysqli->query($q);
$mesecna_prodaja = $po->fetch_assoc();
此查询从数据库中选择月度销售数据。如果我在phpMyAdmin中运行相同的查询,我会得到正确的结果。所有销售月份,每月总销售额。问题是,在上个月,fet_assoc只返回一个结果后,$ mesecna_prodaja?我如何获取所有数据,如phpMyAdmin所做的那样?我尝试了fetch_all,但它没有工作(内部服务器错误)。
答案 0 :(得分:0)
我不确定你是如何看待结果的,但是你需要遍历刚刚提取的关联数组以查看所有结果。
中描述的内容/* fetch associative array */
while ($row = $po->fetch_assoc()) {
printf ("%s (%s)\n", $row["total"], $row["mesec"]);
}
答案 1 :(得分:0)
正如您发现mysqli_fetch_assoc确实为您获取了一行数据,为了获得所有结果,您将不得不遍历结果集的所有行。
有很多方法可以做到这一点,但我会告诉你while循环:
$q = "SELECT SUM(cena) AS total, MONTH( datum ) AS mesec FROM nakupi GROUP BY mesec";
$po = $mysqli->query($q);
//$mesecna_prodaja = $po->fetch_assoc(); //This only gets the first row
//Setup an array to hold all the results
$allMyResults = array();
//Iterate through all the results until there's nothing left (which will cause the while condition to fail)
while ($row = $po->fetch_assoc()) {
//Add $row to allMyResults
$allMyResults[] = $row;
}
var_dump($allMyResults); //You should see all your results here.
这里的关键原则是你的[代码]负责迭代/遍历所有结果。
答案 2 :(得分:0)
php.net是make mysqli :: fetch_all()
$q = "SELECT SUM(cena) AS total, MONTH( datum ) AS mesec
FROM nakupi
GROUP BY mesec";
$po = $mysqli->query($q);
$mesecna_prodaja = $po->fetch_all();
或者您可以使用
$arr = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$arr .= $result->fetch_assoc();
}
} else {
echo "0 results";
}