【发布时间】:2014-03-04 12:40:06
【问题描述】:
目前我有这段代码循环遍历查询的整个结果:
$result = mysqli_query($con, $sql);
$data = array();
while($row = mysqli_fetch_array($result)) {
$name = $row ['name'];
$desc = $row ['description'];
$cat = $row ['category'];
$price = $row ['price'];
$quantity = $row ['quantity'];
$id = $row ['productID'];
$image = $row ['image'];
$arr = array();
$arr ["id"] = $id;
$arr ["name"] = $name;
$arr ["desc"] = $desc;
$arr ["cat"] = $cat;
$arr ["price"] = $price;
$arr ["quantity"] = $quantity;
$arr ["image"] = $image;
array_push($data, $arr);
}
echo json_encode($data);
我想将其更改为仅循环遍历一组结果。我在代码的前面有一个变量,名为$amount,这是我想要的结果数量。
我听说我应该使用mysql_result() 和一个for 循环来计算$amount,但我不确定我现有的代码将如何使用该设置!请提出建议。
编辑:
@Styphon 指出我实际上不需要更改我的迭代代码来解决这个问题。只需在我的 SQL 查询中添加一个LIMIT。
【问题讨论】:
-
为什么不对查询添加限制?为什么你将 row 放入 var 然后 var 放入 array 然后 push 到 data 中?
-
我对 MySQL 没有太多经验,请问这个怎么做?听起来它可以工作!
-
@benharris 看到我的回答