gpt4 book ai didi

php - 从数据库获取数据作为 json 响应

转载 作者:行者123 更新时间:2023-11-30 00:35:29 24 4
gpt4 key购买 nike

在这里,我尝试从数据库获取一些数据,并希望将其显示为 json 响应,以便用户可以获取每个字段。

这是用户如何执行查询

http://localhost/safari/index.php?getbranch=true

这应该给出表中的分支详细信息。

这是执行此操作的 PHP 代码

<?php
if(isset($_GET['getbranch']))
{
$getbranch = $_GET['getbranch'];
if($getbranch == 'true')
{
getbranch($getbranch);
}
}
function getbranch($getbranch)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");

$result = mysqli_query($con,"SELECT division, branch,branchofficename,branchofficecode,status from tbl_branchoffice");
while ($row = @mysqli_fetch_array($result))
{
$result1 = json_encode($row);
}
echo $result1;
}

这有什么问题吗?

JSON 响应:

[{"0":"3","sno":"3","1":"2","division":"2","2":"2","branch":"2","3":"SAFFARI TRAVELS","branchofficename":"SAFFARI TRAVELS","4":"gfgbhghfhf","branchofficecode":"gfgbhghfhf","5":"active","status":"active"},

{"0":"4","sno":"4","1":"2","师":"2","2":"钦奈","分行":"钦奈","3":"chennai","branchofficename":"chennai","4":"br01","branchofficecode":"br01","5":"active","status":"active"} ,{"0":"5","sno":"5","1":"3","师":"3","2":"德里","分行":"德里", "3":"德里","分支机构名称":"德里","4":"br02","分支机构代码":"br02","5":"未激活","状态":"未激活"},{ "0":"6","sno":"6","1":"2","部门":"2","2":"类加罗尔","分公司":"类加罗尔","3 ":"类加罗尔","分支机构名称":"类加罗尔","4":"br03","分支机构代码":"br03","5":"事件","状态":"事件"},{"0 ":"7","sno":"7","1":"3","部门":"3","2":"浦那","分支":"浦那","3": "pune","branchofficename":"pune","4":"br04","branchofficecode":"br04","5":"notactive","status":"notactive"}]

最佳答案

更改您的 while 循环

$result1 = array();
while ($row = @mysqli_fetch_array($result))
{
array_push($result1 , $row);
}

这样,您就收集了 $result1 中的所有结果

现在你可以对其进行编码

echo  $result1 = json_encode( $result1);  

我更喜欢使用array,忽略json_encode行代码,

foreach($result1 as $resultset){
//resultset contains one single row of table
foreach($resultset as $column => $columnValue){
//assuming your table column name as 'city'
if($column == 'city' && $columnValue == 'pune' ){
//displaying array of table which satisfies the condition
var_dump($resultset );

}
}
}

关于php - 从数据库获取数据作为 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22217216/

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