在 MySQL 中使用预准备语句插入或更新


Insert or Update with prepared statements in MySQL

尝试使用 php 的 pdo 中的预准备语句插入或更新 sql。首先我想使用REPLACE INTO命令,但它给了我一个错误,因为我的索引上有一个外键。阅读我必须使用INSERT...ON DUPLICATE KEY UPDATE语法才能使其工作,但我不清楚如何使用预准备语句来做到这一点。有什么解决方案吗?谢谢。

sql 是 :

$sql="REPLACE INTO fn_currencies(id,short,name,buy,sell,date) VALUES (:id,:short,:name,:buy,:sell,:update)";

UPD:我在 Yii 中进行此查询,该查询在 PDO 上使用个人包装器。当我使用未命名的参数时,我收到这种类型的错误:

CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: INSERT INTO `fn_currencies` (id,short,name,buy,sell,date) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=?,short=?,name=?,buy=?,sell=?,date=? 

当我使用具有不同名称的命名参数进行插入和更新时,如前所述。.我没有收到任何错误,也没有将数据插入我的数据库中。下面是数据库的架构:

CREATE TABLE IF NOT EXISTS `fn_currencies` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `short` varchar(4) NOT NULL,
  `name` varchar(200) NOT NULL,
  `buy` decimal(10,4) NOT NULL,
  `sell` decimal(10,4) NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
ALTER TABLE `fn_currencies`
  ADD CONSTRAINT `FK_fn_currencies` FOREIGN KEY (`id`) REFERENCES `fn_operations` (`currency_id`);

感谢DavaRandom,他指出了我代码中的一个错误,但这应该可以解决问题。将命名参数替换为 ?并使用数组合并使 SQL 动态运行,如下所示:

$sql="
    insert INTO fn_currencies(id,short,name,buy,sell,date) 
    VALUES (?,?,?,?,?,?)
    on duplicate key update currencies set 
        short=?, name=?, buy=?, sell=?, update=?";
$values=array("id"=>1, "short"=>36, "name"=>'Bazinga', "sell"=>3.67, "date"=>'2012-08-08');
$db->query($sql, array_merge(array_values($values),array_values($values)));

显然这也将起作用(请参阅整个页面上关于是/否/也许的评论),但上述内容肯定会起作用:

$sql="
    insert INTO fn_currencies(id,short,name,buy,sell,date) 
    VALUES (:id,:short,:name,:buy,:sell,:update)
    on duplicate key update currencies set 
        short=:short, name=:name, buy=:buy, sell=:Sell, update=:update";