反正有没有将json数组发送到服务器端php并将其值插入表中?

时间:2019-08-29 01:05:52

标签: php mysql arrays json angular8

我正在客户端使用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
        )

)

问题是如何在称为regrouper的表中插入该数组的每个对象?

<?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);
?>

我希望表重组器将第一个对象放在一行中,将第二个对象放在另一行

1 个答案:

答案 0 :(得分:1)

您不需要致电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);