我有这段代码
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["user_id"] = $row["user_id"];
$product["user_name"] = $row["user_name"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
它给了我这个结果
{"products":[{"user_id":"2","user_name":"BOZ2"},{"user_id":"25","user_name":"POZ"},{"user_id":"28","user_name":"a"}],"success":1}
现在我正在使用......
$row = $stmt->fetch();
if ($row) {
$sql = "select statement";
$stmt = $db->prepare( $sql );
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
$response["products"] = array();
$product["user_name"] = $row["user_name"];
$product["user_id"] = $row["user_id"];
// convert to json
$json = array_push($response["products"], $product);
// echo the json string
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
它给了我这个......同样的结果
{"products":[{"user_name":"BOZ2","user_id":"2"}],"success":1}{"products":[{"user_name":"BOZ2","user_id":"2"}],"success":0,"message":"success"}
如何让它循环遍历所有结果
答案 0 :(得分:0)
fetchAll返回数组中的所有行。你只需要这个
$sql = "select statement";
$stmt = $db->prepare( $sql );
$stmt->execute();
$response = array();
$response["products"] = $stmt->fetchAll( PDO::FETCH_ASSOC );
$response["success"] = 1;
echo json_encode($response);