PHP REST API 404

  • 本文关键字:API REST PHP php json
  • 更新时间 :
  • 英文 :


我是第一次在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);

mysqli_fetch_assoc之前,请检查结果是还是。如果没有记录,mysqli_query返回布尔值 false

你可以有这样的东西:

if(!$result) {
http_response_code(404);
//response message
}
else {
//process result 
}

现在一切正常。我解决了问题:(

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 );

最新更新