我在php中创建了一个API以从mysql数据库中搜索,数据库给了我5个结果,但是运行时在我的php API中...它没有显示任何数据,因为以下响应是我的API代码。
这是我的Php的API,我将包名作为标头中的输入,然后在mysql数据库中找到该输入,这应返回5个结果给我,而且我必须将这5个结果编码为json并作为响应发送。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "package";
//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check Connection
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$packagename = (print_r($_SERVER['HTTP_PACKAGENAME'],true));
//$pass = (print_r($_SERVER['HTTP_PASSWORD'],true));
//print_r($_SERVER);
//print_r(apache_request_headers());
$sql = "select * from `package_details` where Package_Name='$packagename' ";
$result = $conn->query($sql);
if($result->num_rows>0) {
//$response["package_details"] = array();
//Output data of each row
while($row = $result->fetch_assoc()) {
//temp user array
$user = array();
$user["id"] = $row["id"];
$user["Package_Name"] = $row["Package_Name"];
$user["Package_Day"] = $row["Package_Day"];
$user["Package_Description"] = $row["Package_Description"];
//push single product into final response array
//array_push($response["package_details"], $user);
}
//success
//$response["success"] = "valid";
//echoing JSON response
echo json_encode($user);
} else {
//no products found
$response["package_details"] = array();
while($row = null) {
$user = array();
$user["id"] = $row[null];
$user["Name"] = $row[null];
$user["Contact_Number"] = $row[null];
$user["Email_Id"] = $row[null];
//push single product into final response array
array_push($response["package_details"], $user);
}
$response["success"] = "invalid";
//$response["success"] = "invalid";
//$response["message"] = "No Products Found";
//echo no users JSON
echo json_encode($response);
}
?>
最佳答案
您只是对最后一个$user
进行json编码,而不是应放入$response['package_details']
的用户数组
请参阅下面的修改后的代码
$response = array();
if($result->num_rows>0) {
while($row = $result->fetch_assoc()) {
$user = array();
$user["id"] = $row["id"];
$user["Package_Name"] = $row["Package_Name"];
$user["Package_Day"] = $row["Package_Day"];
$user["Package_Description"] = $row["Package_Description"];
//push single product into final response array
$response["package_details"][] = $user;
}
//success
$response["success"] = "valid";
} else {
//no products found
$response["success"] = "invalid";
$response["message"] = "No Products Found";
}
echo json_encode($response);
关于php - 如何在php中从mysql编码多个结果…我得到5个结果,但是当我运行API时,它没有以JSON格式显示任何数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42788363/