<?php
$successreturn[]=array(
"id"=>"any",
"firstname"=>"any",
"lastname"=>"any",
"dateofbirth"=>"any",
"city"=>"any",
"gender"=>"any"
);
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
$sql= "SELECT * FROM Employees";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$value=0;
if(!$result){
echo "Connection Failed " .mysqli_connect_error($result);
}
while($row = mysqli_fetch_assoc($result)){
$successreturn[$value]['id'] =$row['id'];
$successreturn[$value]['firstname'] =$row['firstname'];
$successreturn[$value]['lastname'] =$row['lastname'];
$successreturn[$value]['dateofbirth'] =$row['dateofbirth'];
$successreturn[$value]['city'] =$row['city'];
$successreturn[$value]['gender'] =$row['gender'];
$value++;
};
echo json_encode($successreturn);
?>
输出:
[{"id":"any","firstname":"any","lastname":"any","dateofbirth":"any","city":"any","gender":"any"}]
我正在尝试将JSON值返回到我的角度服务中。但是当表中没有更多行时。它将Colomn值返回为“any”。 为什么会这样?如何返回没有值的空行?
答案 0 :(得分:0)
当没有选择行时,while循环没有执行,并且初始$ successreturn数组返回值为&#39;任何&#39; 如果没有选择行则返回没有值
只需更改此
$successreturn[]=array(
"id"=>"any",
"firstname"=>"any",
"lastname"=>"any",
"dateofbirth"=>"any",
"city"=>"any",
"gender"=>"any");
到
$successreturn[]=array(
"id"=>"",
"firstname"=>"",
"lastname"=>"",
"dateofbirth"=>"",
"city"=>"",
"gender"=>"");
修改: - 强>
$successreturn=[];
在视图中检查值是否为空,然后显示数据,否则显示数据。 我会帮助你。
答案 1 :(得分:0)
您需要以不同的方式控制程序流程
<?php
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
// first only select what you want to use from the row
$sql= "SELECT `id`,`firstname`,`lastname`,
`dateofbirth`,`city`,`gender`
FROM Employees";
$result = mysqli_query($conn,$sql);
if(!$result){
// you only use `mysqli_connect_error` to get connection errors
// use mysqli_error($result) for normal query errors
echo "Query failed " . mysqli_error($result);
echo json_encode(array('error'=>'Query failed'));
exit;
}
if ( mysqli_num_rows($result) > 0 ) {
while($row = mysqli_fetch_assoc($result)){
// now as you only have what you want in your assoc array
$rows[] = $row;
}
echo json_encode($rows);
} else {
// no data returned from query
// return something so the calling code knows what to do
echo json_encode(array('error'=>'No data in table'));
}
?>