product.php
class B
{
public:
B() = default;
virtual ~B() = default;
private:
A _a = A(3);
};
read.php
<?php
class Product
{
private $conn;
private $table_name = "category";
public $image_name;
public $file_s;
public function __construct($db){
$this->conn = $db;
}
function read()
{
$query = "SELECT * FROM ".$this->table_name." order by category_name";
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
}
我已经创建了一个可以正常工作的简单REST api,但是现在的问题是我对如何在php中添加REST api的响应代码和响应消息一无所知?
谢谢
答案 0 :(得分:0)
这是将HTTP状态设置为200的方式:
header("HTTP/1.1 200 OK");
在您的代码中应用此代码:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("HTTP/1.1 200 OK");
include_once 'dbase.php';
include_once 'product.php';
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
$stmt = $product->read();
$num = $stmt->rowCount();
if($num>0)
{
$products_arr=array();
$products_arr["data"]=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$product_item=array(
"image_name" => $image_name,
"image_url" => $file_s
);
array_push($products_arr["data"], $product_item);
}
echo json_encode($products_arr);
}
else{
echo json_encode(
array("message" => "No products found.")
);
}
?>
答案 1 :(得分:0)
我认为这可以解决您的问题
echo json_encode( array(“ status” =“ 404”,“消息” =>“未找到产品。”) );
状态是您的回复代码。 您可以根据自己的需要修改此响应代码
答案 2 :(得分:0)
header("HTTP/1.1 200 OK");
//此行会将服务器响应设置为200
header("HTTP/1.1 404 ERROR");
//这将引发404错误。您可以将此代码更改为任何相应的代码