gpt4 book ai didi

php - Json 数组不显示 PHP 脚本到 SQL 数据库的 5 行或更多行

转载 作者:行者123 更新时间:2023-11-30 22:06:31 26 4
gpt4 key购买 nike

当我尝试在我的数据库上执行基本的 CRUD 操作时,但在这里当我尝试使用 php 脚本从我的数据库中获取一行时,我从我的数据库中看到了正确的数据,但是当我把de 数据库上的更多行,我试图获取数据,但它从未出现。

我正在使用这个 PHP 脚本

<?php 
//Importing Database Script
require_once('Connectdb.php');

//Creating sql query
$sql = "SELECT * FROM ensaladas ";

//getting result
$r = mysqli_query($con,$sql);

//creating a blank array
$result = array();

//looping through all the records fetched
while($row = mysqli_fetch_assoc($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"ensid"=>$row['ensid'],
"nombre"=>$row['nombre'],
"precio"=>$row['precio'],
));
}

//Displaying the array in json format
echo json_encode(array('result'=>$result));

mysqli_close($con);
?>

然后给出下一个结果:

enter image description here

我在表格有 2 行时使用它,当我放置另一行时,代码停止工作。数据库的表有 3 个字段:ensid、nombre、precio。正如您在这里看到的:

enter image description here

PD: 我正在使用这个脚本来获取 Android APP 上的数据

最佳答案

错误检查

做一些error checking就你而言。您还可以尝试在系统后端 (PhpMyAdmin) 运行查询。

获取数据

因为您已经在使用 mysqli_* API,请尝试使用 prepared statement相反:

$stmt = $con->prepare("SELECT ensid, nombre, precio FROM ensaladas");
$stmt->execute();
$stmt->bind_result($ensid, $nombre, $precio);
while($stmt->fetch()){

array_push($result, array(
"ensid"=>$ensid,
"nombre"=>$nombre,
"precio"=>$precio,
));

}
$stmt->close();

显示数据

然后您现在可以使用以下方式显示所有数据:

echo json_encode($result);

或者如果您想要结果中的特定行,您可以使用索引:

echo json_encode($result[$x]); /* $x REPRESENTS THE INDEX; INTEGER VALUE */

或者从特定行获取特定数据:

echo json_encode($result[$x]['ensid']); /* EITHER ensid, nombre, or precio */

关于php - Json 数组不显示 PHP 脚本到 SQL 数据库的 5 行或更多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com