I making PHP API to insert multiple rows of JSON object data. My JSON data format is like this:
(I receive this below format in console log for console.log(this.state.cartItems[]). in REACT)
0: {SparePartID: "34", qty: 1, Price: "500", OrderID: "14"}
1: {SparePartID: "35", qty: 1, Price: "250", OrderID: "14"}
2: {SparePartID: "36", qty: 1, Price: "430", OrderID: "14"}
My PHP Api code is below:
---> part_order_details.php
header("Access-Control-Allow-Origin: http://localhost/Auth/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/database.php';
include_once '../objects/order.php';
$database = new Database();
$db = $database->getConnection();
$order = new Order($db);
$a = file_get_contents("php://input");
$data = json_decode($a, true);
if($order->orderDetails($data)){
http_response_code(200);
echo json_encode(array(
"message" => "All rows of Order Details are inserted.",
));
}
else{
http_response_code(400);
echo json_encode(array("message" => "Sorry! Error while inserting rows of order details"));
}
and -----> order.php is:
class Order{
private $conn;
public $SparePartID;
public $OrderID;
public $Price;
public $Quantity;
public function __construct($db){
$this->conn = $db;
}
function orderDetails($arr)
{
$query= "INSERT INTO sparepartorderdetails (SparePartID, OrderID, Quantity, Price) VALUES
(:SparePartID, :OrderID, :qty, :Price) ";
$stmt = $this->conn->prepare($query);
foreach($arr as $item)
{
$stmt->bindValue(':SparePartID', $item[0]);
$stmt->bindValue(':qty', $item[1]);
$stmt->bindValue(':Price', $item[2]);
$stmt->bindValue(':OrderID', $item[3]);
if($stmt->execute()){
return true;
}
else{
$arr = $stmt->errorInfo();
print_r($arr);
}
}
}
}
For now, Im trying to test PHP API with POSTMAN. so Im sending this data in Postman body for POST request:
{
"0":
{"SparePartID": "34",
"qty": "1",
"Price": "500",
"OrderID": "14"},
"1":
{"SparePartID": "35",
"qty": "1",
"Price": "250",
"OrderID": "14"}
}
But the POSTMAN shows ERROR Status: 400 Bad Request with msg: { "message": "Sorry! Error while inserting rows of order details" }
I searched this problem a lot, but no solution. Am I missing something or using wrong way to insert multiple JSON rows?
returnwithin your loop. Perhaps keep track of which records inserted successfully and which didn't, and then report the results at the end. In terms of your execute seemingly returning false, look into PDO error handling to help you spot the exact issue.