簡體   English   中英

反正有沒有將json數組發送到服務器端php並將其值插入表中?

[英]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
        )

)

問題是如何在稱為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);
?>

我希望表重組器在一行上有第一個對象,在另一行上有第二個對象

您不需要兩次調用json_decode() 您已經完成解碼了

$decoded = json_decode($json);

因此,插入時無需使用json_decode($item)

json_decode()使用true第二個參數,以便為每個項目創建一個關聯數組而不是對象。 然后,您可以將該數組直接傳遞給$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM