У меня есть несколько прекрасно работающих PHP API для базовых операций CRUD , где пользователь может создавать, читать, обновлять и удалять любые данные формы.Теперь я хочу вставить изображения .Я использую REACT для клиентской стороны .
Поэтому я хочу изменить мои php API "create_product", чтобы он мог принимать JSON закодированные данные (загрузил img) от пользователя и вставьте его в базу данных.А также обратное действие, при котором он будет показывать изображение продукта всякий раз, когда вызывается API чтения.
I искал это много , но они дают другие решения, но не с JSON формат или API.Я знаю обычный способ загрузки изображения в php, но не могу понять это в остальных API.
ПОЖАЛУЙСТА, ПОМОГИТЕ МНЕ.Я был бы действительно СПАСИБО.вот мой код PHP API :
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// files needed to connect to database
include_once 'config/database.php';
include_once 'objects/product.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// instantiate product object
$user = new Product($db);
// get posted data
$data = json_decode(file_get_contents("php://input"));
// make sure data is not empty
if(
!empty($data->Name) &&
!empty($data->Price) &&
!empty($data->Description) &&
!empty($data->VehicleID)
) {
// set product property values
$user->Name = $data->Name;
$user->Price = $data->Price;
$user->Warranty = $data->Warranty;
$user->Description = $data->Description;
$user->Status = $data->Status;
$user->SubCatPartID = $data->SubCatPartID;
$user->VehicleID = $data->VehicleID;
$user->VendorID = $data->VendorID;
if ($user->create()) {
http_response_code(200);
echo json_encode(array("message" => "Spare Part Record is inserted Successfully"));
}
else {
http_response_code(400);
echo json_encode(array("message" => "Unable to insert Spare Part... Sorry..."));
}
}
else{
http_response_code(400);
echo json_encode(array("message" => "Unable to create product. Data is EMPTY."));
}
?>
вот php create () метод:
class Product{
// database connection and table name
private $conn;
private $table_name = "sparepart";
// object properties
public $SparePartID;
public $Name;
public $Price;
public $Warranty;
public $Description;
public $Status;
public $SubCatPartID;
public $VehicleID;
public $VendorID;
public function __construct($db){
$this->conn = $db;
}
function create(){
// insert query
$query = "INSERT INTO " . $this->table_name . "
SET
Name = :Name,
Price = :Price,
Warranty = :Warranty,
Description = :Description,
Status = :Status,
SubCatPartID = :SubCatPartID,
VehicleID = :VehicleID,
VendorID = :VendorID";
// prepare the query
$stmt = $this->conn->prepare($query);
// sanitize
$this->Name=htmlspecialchars(strip_tags($this->Name));
$this->Price=htmlspecialchars(strip_tags($this->Price));
$this->Warranty=htmlspecialchars(strip_tags($this->Warranty));
$this->Description=htmlspecialchars(strip_tags($this->Description));
$this->Status=htmlspecialchars(strip_tags($this->Status));
$this->SubCatPartID=htmlspecialchars(strip_tags($this->SubCatPartID));
$this->VehicleID=htmlspecialchars(strip_tags($this->VehicleID));
$this->VendorID=htmlspecialchars(strip_tags($this->VendorID));
$stmt->bindParam(':Name', $this->Name);
$stmt->bindParam(':Price', $this->Price);
$stmt->bindParam(':Warranty', $this->Warranty);
$stmt->bindParam(':Description', $this->Description);
$stmt->bindParam(':Status', $this->Status);
$stmt->bindParam(':SubCatPartID', $this->SubCatPartID);
$stmt->bindParam(':VehicleID', $this->VehicleID);
$stmt->bindParam(':VendorID', $this->VendorID);
if($stmt->execute()){
return true;
}
return false;
}
А вот мой вызов API в REACT JS (для создания продукта):
onSubmit (e)
{
e.preventDefault();
const sparepart = {
Name: this.state.Name,
Price: this.state.Price,
Warranty: this.state.Warranty,
Description: this.state.Description,
Status: this.state.Status,
SubCatPartID: this.state.SubCatPartID,
VehicleID: this.state.VehicleID,
VendorID: this.state.vendor.VendorID }
axios.post('http://localhost/Auth/api/insert_parts.php', sparepart)
.then((result) => {
console.log(result.data);
alert("Congratulations! New Spare Part has been added!");
this.setState({redirectToReferrer: true});
return result;
})
.catch(error => {
if (error) {
console.log("Sorry cannot insert data");
console.log(error); }
});
}