[英]getting data from database as a json response
在这里,我试图从数据库中获取一些数据,并希望将其显示为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”,“ division”:“ 2”,“ 2”:“ chennai”,“ branch”:“ chennai”,“ 3“:” chennai“,” branchofficename“:” chennai“,” 4“:” br01“,” branchofficecode“:” br01“,” 5“:” active“,” status“:” active“},{” 0“:” 5“,” sno“:” 5“,” 1“:” 3“,” division“:” 3“,” 2“:” delhi“,” branch“:” delhi“,” 3“ :“ delhi”,“ branchofficename”:“ delhi”,“ 4”:“ br02”,“ branchofficecode”:“ br02”,“ 5”:“ notactive”,“ status”:“ notactive”},{“ 0” :“ 6”,“ sno”:“ 6”,“ 1”:“ 2”,“除法”:“ 2”,“ 2”:“班加罗尔”,“分支”:“班加罗尔”,“ 3”:“ bangalore“,” branchofficename“:” bangalore“,” 4“:” br03“,” branchofficecode“:” br03“,” 5“:” active“,” status“:” active“},{” 0“:” 7“,” sno“:” 7“,” 1“:” 3“,”除“:” 3“,” 2“:”浦那“,”分支“:”浦那“,” 3“:”浦那“ ,“ branchofficename”:“浦那”,“ 4”:“ br04”,“ branchofficecode”:“ br04”,“ 5”:“无效”,“状态”:“无效”}]
$result1 = array();
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[] = $row;
}
echo json_encode($result1);
}
首先将结果的每一行收集到数组result1中,然后最后输出$ result1数组的json_encode
更改while
循环
$result1 = array();
while ($row = @mysqli_fetch_array($result))
{
array_push($result1 , $row);
}
这样做,您已经在$result1
收集了所有结果
现在您可以对其进行编码
echo $result1 = json_encode( $result1);
我将更喜欢使用array
,ignor 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 );
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.