[英]PHP REST API 404
I am doing it for the first time API in Php.我第一次在 Php 中做 API。 It finds one product by id.它通过 id 找到一个产品。 If there is a product in the database -> code 200 if it is not -> code 404. But 404 not working.如果数据库中有产品 -> 代码 200 如果没有 -> 代码 404。但 404 不起作用。
What am I doing wrong?我究竟做错了什么?
1. code 200 it works Output: 1.代码200它工作Output:
/get_id2.php?id=39
records 0
id "39"
caption "Product1"
filename "Image01.jpg"
2. code 404 did not work Output: 2. 代码 404不起作用 Output:
/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
Code:代码:
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);
Before mysqli_fetch_assoc
you check if the result is true or false .在mysqli_fetch_assoc
之前检查结果是true还是false 。 In case of no records, mysqli_query
returns a boolean false .如果没有记录, mysqli_query
返回boolean false 。
You could have something like:你可以有类似的东西:
if(!$result) {
http_response_code(404);
//response message
}
else {
//process result
}
Everything works now.现在一切正常。 I solved the problem:)我解决了这个问题:)
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.