这是我第一次在Php中使用API。它用id找到一个产品。如果数据库中存在产品,则->代码200 (如果不是->代码404 )。但404不起作用
我做错了什么?
1.代码200的输出:
/get_id2.php?id=39
records 0
id "39"
caption "Product1"
filename "Image01.jpg"2.代码404没有工作输出:
/get_id2.php?id=39999 (there is no product)
SyntaxError: JSON.parse: unexpected end of data at line 3 column 1 of the JSON data代码:
header("Content-Type: application/json; charset=UTF-8");
include_once('config_setup.php');
$id = $_GET['id'];
$sql = "SELECT * ";
$sql .= "FROM photographs ";
$sql .= "WHERE id='" . db_escape($db, $id) . "'";
$result = mysqli_query($db, $sql);
confirm_db_connect($result);
// products array
$products_arr=array();
$products_arr["records"]=array();
$message = [];
while($photo = mysqli_fetch_assoc($result)) {
if($photo['caption']!=null){
extract($photo);
$product_item = array(
"id" => $id,
"caption" => $caption,
"filename" => $filename,
);
// set response code - 200 OK
http_response_code(200);
array_push($products_arr["records"], $product_item);
echo(json_encode($products_arr));
} else {
// set response code - 404 Not found
http_response_code(404);
// tell the user product does not exist
echo json_encode(array("message" => "Product does not exist."));
}
}
mysqli_free_result($result);
db_disconnect($db);发布于 2020-05-21 10:09:55
在mysqli_fetch_assoc之前,您检查结果是true还是false。如果没有记录,mysqli_query将返回一个布尔值false。
你可以有这样的东西:
if(!$result) {
http_response_code(404);
//response message
}
else {
//process result
}发布于 2020-05-21 10:26:37
现在一切都正常了。我解决了问题:)
header("Content-Type: application/json; charset=UTF-8");
include_once('config_setup.php');
$id = $_GET['id'];
$sql = "SELECT * ";
$sql .= "FROM photographs ";
$sql .= "WHERE id='" . db_escape( $db, $id ) . "'";
$result = mysqli_query( $db, $sql );
confirm_db_connect( $result );
$photo = mysqli_fetch_assoc( $result );
$id = $photo['id'];
$caption = $photo['caption'];
$filename = $photo['filename'];
if ($photo['caption'] != null) {
// create array
$product_arr = array(
"id" => $photo['id'],
"caption" => $photo['caption'],
"filename" => $photo['filename']
);
// set response code - 200 OK
http_response_code(200);
echo json_encode( $product_arr );
} else {
// set response code - 404 Not found
http_response_code(404);
// tell the user product does not exist
echo json_encode(array("message" => "Product does not exist."));
}
mysqli_free_result( $result );
db_disconnect( $db );https://stackoverflow.com/questions/61931690
复制相似问题