php - PDO:使用增量键在 MySQL 中插入数组

标签 php mysql arrays pdo sql-insert

<分区>

我查看了所有其他关于在 PDO 中插入数组的帖子,但一直无法弄清楚具体如何操作。我要拿这个:

$images_ar = 
Array
(
[0] => Array
    (
        [0] => 100
        [1] => Lips
        [2] => 50
        [3] => 50
        [4] => 127
        [5] => 257
        [6] => 9998
        [7] => 70
        [8] => xxx
    )

[1] => Array
    (
        [0] => 103
        [1] => Ball
        [2] => 117
        [3] => 114
        [4] => 128
        [5] => 44
        [6] => 9997
        [7] => 70
        [8] => xxx
    )

[2] => Array
    (
        [0] => 104
        [1] => Sun
        [2] => 94
        [3] => 91
        [4] => 48
        [5] => 277
        [6] => 9996
        [7] => 70
        [8] => xxx
    )

)

然后执行 PDO 插入,其中 [0] = image_id 和 [9] = avatar_id。

利用其他帖子,到目前为止,我有这个:

$images_ar = array_chunk($ar, 9);

$handler->beginTransaction();

foreach($images_ar as $row){
   $question_marks[] = "('',?,?,?,?,?,?,?,?)";
}

$query = $handler->prepare ("INSERT INTO avatars (ID, img_id, title, width, height, top, left, zindex, userid, avatar_id) VALUES " . implode(',', $question_marks);

$query->execute($ar);

$handler->commit();

错误:
fatal error :消息为“SQLSTATE[42000]”的未捕获异常“PDOException”:语法错误或访问冲突:1064 您的 SQL 语法有错误;查看与您的 MySQL 服务器版本对应的手册,了解在 'left, zindex, userid, avatar_id) 附近使用的正确语法 VALUES ('',?,?,?,?,?,?,?,?),(' ',?,?,?,?,?,?,?,?' 在 ...\save.php:52 的第 1 行 堆栈跟踪:0 ...\save.php(52): PDO->prepare('INSERT INTO ava...') 1 {主要} 在 52

行的 ...\save.php 中抛出

我走在正确的轨道上吗?

谢谢大家! =D

最佳答案

我能够通过使用 array_combine() 方法更改键来让它工作。

最终代码为:

$images_ar = array_chunk($ar, 9);
$keys = array('img_id', 'title', 'width', 'height', 'top', 'lef', 'zindex', 'userid', 'avatar_id');
foreach ($images_ar as $row) {  
    $list[] = array_combine($keys, array_values($row));
}
$handler->beginTransaction();
foreach($images_ar as $row){
   $question_marks[] = "(DEFAULT,?,?,?,?,?,?,?,?,?)";
}
$query = $handler->prepare ("INSERT INTO avatars (ID, img_id, title, width, height, top, lef, zindex, userid, avatar_id) VALUES " . implode(',', $question_marks));
$query->execute($ar);
$handler->commit();

关于php - PDO:使用增量键在 MySQL 中插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25093497/

相关文章:

php - 如何使用 jQuery AJAX $.post 来存储 PHP $_SESSION 变量?

php - 如何在 javascript 颜色框中调用 php 变量

php - 移除 Switch 语句

java - 从两个不同的表插入一个表并具有自动增量值

php - 多个复选框插入不正确

php - 如何在 Laravel 5.7 中获取 json 值?

c++ - 如何在空数组中添加用户给定的字符串并在C++中查找其长度

Javascript - 带有 boolean 键的数组?

php - WHOIS API JSON 数组内容

mysql - 存在多个实例时如何仅返回列值的 1 个(特定)实例