Answer the question
In order to leave comments, you need to log in
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
$products
Array
(
[0] => Array
(
[id] => 0
[name] => Ноутбук
[code] => 2028029
[price] => 2000
)
[1] => Array
(
[id] => 0
[name] => Ноутбукк
[code] => 2028069
[price] => 2498
)
)
$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();
INSERT INTO
REPLACE INTO
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question