PDO 语法错误或使用内爆的访问冲突

PDO Syntax error or access violation using implode

我有一个要存储在数据库中的标签列表。名为 "tags" 的 table 有 2 列:id(自动递增)和 tag(varchar)。目标是将数组的每个标记附加到 "tag" 列的唯一行。我得到的错误是:

Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25) VALUES ('al' at line 1 in C:\xampp\htdocs\cmanager\draft.php on line 36 New tags created successfully Notice: Use of undefined constant tags - assumed 'tags' in C:\xampp\htdocs\cmanager\draft.php on line 34

代码如下:

<?php
include('../config.php');

$tagList = array('black', 'purple', 'alpha', 'pink', 'normal', 'green', 'shininess', 'specular', 'blue', 'orange',
    'nylon', 'stretched', 'brown', 'yellow', 'green', 'suede', 'wood', 'linen', 'red', 'white', 'no', 'tile', 'gray',
    'velvet', 'mauve', 'white');

sort($tagList);
print_r($tagList);

    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=store", $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        echo "Connected to database \r\n";


        foreach ($tagList as $k => $v) {
            $prep[':' . $k] = $v;

            $bind = ':' . implode(',:', array_keys($tagList));
//            $sql = 'INSERT INTO tags (tag) ' .
//                ' VALUES (:bind)';
            $sql = 'INSERT INTO ' . tags . '(' . implode(',', array_keys($tagList)) . ') ' . 'VALUES (' . $bind . ')';
            $stmt = $dbh->prepare($sql);
            $stmt->execute(array_combine(explode(',', $bind), array_values($tagList)));
            echo "New tags created successfully \r\n";

        }
    } catch (PDOException $e) {
        echo $e->getMessage();
    }

我不明白这是什么错误。有人可以帮我吗?谢谢

首先,你有一个语法错误:

'INSERT INTO ' . tags . '('

必须是:

'INSERT INTO tags ('

然后,你有一个奇怪的 foreach,其中理论上执行 26 个查询,每个 $tagList 值一个。理论上,因为循环一开始就崩溃了。

在第一个循环中,这是发送到您的数据库的查询:

INSERT INTO tags(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25) VALUES (:0,:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16,:17,:18,:19,:20,:21,:22,:23,:24,:25)

如果要在 tag 字段中一次插入多个值,正确的语法是:

INSERT INTO tags ( tag ) VALUES ( 'tag1' ), ( 'tag2' ), ...

最后但同样重要的是,您必须执行 foreach() 循环来构造您的查询,然后执行查询, 循环之外:

$query = [];
foreach( ... )
{
    // Your stuff to set the query here
    $query[] = "( :varNameToBind )";
}

$query = "INSERT INTO tags (tag) VALUES " . implode( ", ", $query );

echo $query;   //  Test your query
die();         //  then remove these lines

$stmt = $dbh->prepare( $query );
$stmt->execute( ... );

你的绑定数组构造对我来说似乎很好。