执行数值数组时 PHP PDO 错误

标签 php mysql sql arrays pdo

我正在制作一个向数据库添加订单的脚本。当插入(很多字段时,我不能通过每次用户访问页面时查询数据库 50 次来简单地做到这一点,因此它必须进入一个查询。

我制作了一个脚本,可以动态添加选定数量的记录,这些记录链接到数组中给定的数据量。

但是每当我尝试执行查询时,它都会给出一个错误,指出我的语法不正确。

我的代码:

private function addOrderDetails($products, $orderID) {
    # Base of the query (will be the end result)
    $query = 'INSERT INTO `Database`.`orderDetails` (
        `amount`, 
        `price`, 
        `tax`, 
        `product_id`, 
        `order_id`
    ) VALUES (:?, :?, :?, :?, :?)';

    # Added to the query if there are more than 1 products
    $queryExtension = ', (:?, :?, :?, :?, :?)';
    $queryPayload   = array();

    # Loop through all products and add them to the query payload
    foreach ($products as $counter => $productArray) {
        # Add all values individually
        foreach ($productArray as $value) {
            array_push($queryPayload, $value);
        }

        # Add the orderID at the end and extend the query (if the key is more than 0)
        array_push($queryPayload, $orderID);
        if ($counter > 0) $query .= $queryExtension;
    }

    # Execute the array
    $query  = $this->DB->prepare($query);
    $query->execute($queryPayload);        # Error on this exact line, if I put an exit; here it throws no error.
}

我的数据数组:

array(
    array(
        'amount'    => 50,
        'price'     => 10,
        'tax'       => 2,
        'productID' => 5
    ),
    array(
        'amount'    => 27,
        'price'     => 19,
        'tax'       => 6,
        'productID' => 15
    ),
    array(
        'amount'    => 492,
        'price'     => 2300,
        'tax'       => 4.5,
        'productID' => 50
    )
);

我的错误:

Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':'50', :'10', :'2', :'5', :'42'), (:'27', :'19', :'6', :'15', :'42'), (:'492', :' at line 7' in (webroot)
Stack trace:
#0 (webroot): PDOStatement->execute(Array)
#1 (webroot): Database->addOrderDetails(Array, '42')
#2 (webroot): Database->addOrder(1, '1', Array)
#3 {main}

最佳答案

就像我在评论中所说,命名占位符以冒号开头。您似乎没有使用命名占位符,因此常规问号即可。 IE 将 :? 替换为 ?

也就是说,您似乎错过了使用准备好的语句的最佳部分:您可以使用不同的值重复使用准备好的查询。当根本不需要时,您正在添加并添加到查询字符串:

$query = 'INSERT INTO `Database`.`orderDetails` (
        `amount`, 
        `price`, 
        `tax`, 
        `product_id`, 
        `order_id`
    ) VALUES (?, ?, ?, ?, ?)';
$stmt = $pdo->prepare($query);
$pdo->beginTransaction();//best use transactions here, though
foreach ($products as $counter => $productArray)
{
    $bind = array_values($productArray);//though strictly speaking, this isn't required
    $stmt->execute($bind);//add this array
    $stmt->closeCursor();
}
$pdo->commit();

准备好的语句是预编译、预优化的查询,只需要输入(即要插入的值)即可执行。如果可以提前编译和优化查询,为什么不能多次使用相同的资源呢?正如您从上面的代码中看到的:您可以重复使用该语句,您所要做的就是(这不是严格要求的,但最好这样做) ,是在每次运行完该语句时通知 PDO(和 DB)。 PDOStatement::closeCursor 会为您完成此操作。

因为您尝试在一个查询中插入数据,所以我建议使用事务。这样,如果其中一个查询失败,则会抛出异常,并且您可以撤消迄今为止运行的所有查询:

try
{
    $pdo->beginTransaction();
    //same code as above
    $pdo->commit();//save changes
}
catch (PDOException $e)
{//something went wrong
    $pdo->rollBack();//undo changes
}

关于执行数值数组时 PHP PDO 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25702433/

相关文章:

php - Wordpress 自定义表格或自定义帖子类型?

php - MySQL 到 MSSQL PHP 查询转换和速度故障排除

.net - 如何更改 SQL 中的列属性?

mysql - SQL - 选择具有最大值的所有行

mysql - 更新行数

php - 将图片调整/裁剪/填充到固定大小

php - 使用未知数量的参数查询数据库

javascript - 使用ajax将时间以秒为单位传递给div

php - 检查新间隔是否重叠 - MySQL(或 PHP)

mysql - 删除在单独表中找不到 userID 的行