有没有办法将 json 数组发送到服务器端 php 并将其值插入 table?

Is there anyway to send a json array to server side php and insert it's values in a table?

我在客户端使用 ANgular 8,在服务器端使用 PHP 7。 我在使用该数组的值通过查询插入它们时遇到问题。

我按 print_r 显示数组,它显示如下内容:

Array
(
    [0] => stdClass Object
        (
            [idprod] => 8
            [prix] => 2
            [qte] => 1
            [refCmd] => 35
        )

    [1] => stdClass Object
        (
            [idprod] => 9
            [prix] => 2.4
            [qte] => 5
            [refCmd] => 35
        )

)

问题是如何将该数组的每个对象插入到 table 中称为重组器?

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: X-Custom-Header, Origin, Content- 
Type , Authorisation , X-Requested-With");
header("Content-Type: application/json; charset=UTF-8 ");
$json = file_get_contents('php://input');
$decoded = json_decode($json);

$tab = $decoded->tab;
function conn()
{
$dbhost = "localhost";
$user = "root";
$pass = "";
$db = "smart";
$conn = new PDO('mysql:host=localhost;dbname=smart', $user, $pass);
return $conn;
}
$db = conn();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$p = $db->prepare("INSERT INTO regrouper (refCommande, refProduit, prixP, 
qteP) VALUES(:refCmd,:refProduit,:prix,qte)");
foreach ($tab as $item) {
$p->execute([json_decode($item)]);
}
echo json_encode(true);
?>

我希望 table 重组器在一行中有第一个对象,在另一行中有第二个对象

您不需要调用 json_decode() 两次。你做的时候已经解码了

$decoded = json_decode($json);

所以插入时不需要使用json_decode($item)

使用 true 第二个参数 json_decode() 以便它为每个项目创建一个关联数组而不是一个对象。然后你可以将该数组直接传递给 $p->execute() 。您还需要使用 $decoded['tab'] 而不是 $decoded->tab.

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: X-Custom-Header, Origin, Content- 
Type , Authorisation , X-Requested-With");
header("Content-Type: application/json; charset=UTF-8 ");
$json = file_get_contents('php://input');
$decoded = json_decode($json, true);

$tab = $decoded['tab'];
function conn()
{
    $dbhost = "localhost";
    $user = "root";
    $pass = "";
    $db = "smart";
    $conn = new PDO('mysql:host=localhost;dbname=smart', $user, $pass);
    return $conn;
}
$db = conn();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$p = $db->prepare("INSERT INTO regrouper (refCommande, refProduit, prixP, qteP)
                   VALUES(:refCmd,:refProduit,:prix,qte)");
foreach ($tab as $item) {
    $p->execute($item);
}
echo json_encode(true);