如何使用PHP将每个产品的ID,数量,标题,价格,类型从下面的数组插入数据库?

问题描述 投票:-1回答:3

如何使用PHP将每个产品的ID,数量,标题,价格,类型从下面的多维关联数组(来自JSON)插入MySQL数据库?我尝试了foreach循环但不允许回显或插入它,给出错误。我想在数据库中插入值,即插入每个产品的id,qty,title,price,type

    $array = Array
    (
    [page] => 1
    [current] => 100
    [count] => 5
    [pageCount] => 1
    [data] => Array
        (
            [0] => Array
                (
                    [product] => Array
                        (
                            [id] => 11
                            [qty] => 30
                            [title] => abc
                            [price] => 200
                            [type] => men
                        )

                [info] => Array
                    (
                        [brand] => xyz
                    )

            )

        [1] => Array
            (
                [product] => Array
                    (
                        [id] => 12
                        [qty] => 50
                        [title] => dfg
                        [price] => 300
                        [type] => girl
                    )

                [info] => Array
                    (
                        [brand] => jkl
                    )

            )
    )
)
</pre>
multidimensional-array associative-array
3个回答
0
投票
Have you tried something like this?

foreach ($array["data"] as $item) {

echo $item["product"]["id"]; 
echo $item["product"]["qty"];
// and so on for each field
echo $item["info"]["brand"];

}

Else can you be more specific on the format that you need printed?

0
投票

如果要插入数据库,迭代数组,手动中断字段并使用如下代码插入数据库

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

0
投票

最后,我找到了正确的解决方案。请在下面找到代码。

$i=0;
foreach($array['data'][$i] as $a){
     $id = $a['product']['id'];
     $qty = $a['product']['qty'];
     $title = $a['product']['title'];
     $price = $a['product']['price'];
     $type = $a['product']['type'];

     $sql = "INSERT INTO table1 (id,qty,title,price,type) values ('$id','$qty','$title','$price','$type')";

     $i++;                  
}
$i=0;
© www.soinside.com 2019 - 2024. All rights reserved.