P
P
postLaravel2017-09-29 16:48:56
PHP
postLaravel, 2017-09-29 16:48:56

How to write array to database?

Good day! There was such a problem:
When trying to add an array to the database, it gives the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2498' for key 'PRIMARY'' in /home/n/n92687o9/n92687o9.beget.tech/public_html/controllers/ AdminProductController.php:267 Stack trace: #0

Array content:$products
Array
(
    [0] => Array
        (
            [id] => 0
            [name] => Ноутбук
            [code] => 2028029
            [price] => 2000
        )

    [1] => Array
        (
            [id] => 0
            [name] => Ноутбукк
            [code] => 2028069
            [price] => 2498
        )
)

The add code itself:
$db = Db::getConnection();
$sql = 'INSERT INTO product '
                . '(id, name, code, price )'
                . 'VALUES ';
//Формирование запроса:
 $j = 0;
        foreach ($products as $product) {
            if($j > 0) {$sql .= ', ';}
            $sql .= "(";
            $k = 0;
            foreach ($product as $key => $value) {
                $sql .= ":".$key;
                if($k < count($product)-1) {$sql .= ", ";}
                $k++;
            }
            $sql .= ")";
            $j++;
        }
//Формирование параметров для подстановки:
 $result = $db->prepare($sql);
        $j = 0;
        foreach($products as $product) {
            $k = 0;
            foreach($product as $key => $value) {
                $result->bindParam(':'.$key, $value, PDO::PARAM_STR);
                $k++;
            }
            $j++;
        }
$result->execute();

I tried to change it to , then the error disappears, but the same value (2498) is written to the database in all fields. The request is formed correctly (checked), but with the substitution of parameters I have doubts. Is it possible to do this at all? Or is there some not so perverted way to solve this problem? Thanks in advance. INSERT INTOREPLACE INTO

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergej, 2017-09-29
@postLaravel

First, try to learn how to format a post.
dry text without highlighting will not be read.
did you googling your mistake? It is clearly stated here that this is not the case.
If you're too lazy and don't know another language other than Russian, you can use a translator.59ce531af194f745363063.png

E
Evgeny Petrov, 2017-09-29
@EvgenZZ

1. create a TEXT field, 2. $data=json_encode($products), 3. write to the database, 4 read $data=json_decode(TEXT)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question