我做PHP API插入多行JSON对象数据,我的JSON数据格式如下:
- (我在REACT中的console.log(this.state.cartItems[]).* 的console日志中收到以下格式)
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"}
字符串
我的PHP API代码如下:
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"));
}
型
而----->order.php是:
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);
}
}
}
}
型
现在,我尝试用POSTMAN测试PHP API。所以我在Postman body中发送以下数据用于POST请求:
{
"0":
{"SparePartID": "34",
"qty": "1",
"Price": "500",
"OrderID": "14"},
"1":
{"SparePartID": "35",
"qty": "1",
"Price": "250",
"OrderID": "14"}
}
型
但是POSTMAN显示ERRORStatus:400 Bad Request,并带有msg:{“message”:“Sorry!Error while inserting rows of order details”}
我搜索了很多这个问题,但没有解决方案。我错过了什么或使用错误的方式插入多个JSON行?
1条答案
按热度按时间l2osamch1#
你的问题主要在这一行:
第一个月
关于数据绑定:
字符串
当
json_decode
使用true
参数进行关联时,结果数据将是一个数组的数组,其键是字符串,而不是整数。所以你需要将访问每个属性的方式从整数索引改为字符串索引。你可以将bindValue的出现改为这样:型
上述解决方案的替代方案是更改
json_decode
的使用方式。删除true
并更新bindValue
示例以使用对象属性访问(因为现在数据将被解码为Object而不是Arrays):$data = json_decode($a);
个型
关于
$stmt->execute
的最后一个注意事项是,在第一次循环迭代之后,您的函数将return true
(如果成功)。它永远不会完成剩余的插入项。您应该删除早期的return
语句,并找到更好的方法来返回成功/失败指示符。