请告诉我为什么我无法循环遍历所有行并通过此代码将它们返回到数组中(每行中的一行)?
$id= $_POST['uid'];
$rows = [];
$sql = "SELECT customerName, city, date FROM `customers` WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($customerName, $city, $date);
while($stmt->fetch()){
$rows = array($customerName, $city, $date);
}
echo json_encode($rows);
正如您所看到的,我正在使用while($stmt->fetch()){}
,但我只是在echo json_encode($rows);
答案 0 :(得分:2)
您需要使用括号语法([]
)将元素添加到数组中。如果没有它,您将覆盖$rows
:
while($stmt->fetch()){
$rows[] = array($customerName, $city, $date);
}