You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PDO在SQL同字符串值中使用两个bindParam参数报错及多余引号如何解决

问题根源

PDO 预编译机制的安全设计决定了:仅不在单/双引号包裹范围内的占位符才会被识别为待绑定参数,放在引号内的:date_fin、:compte会被直接视为普通文本,不会被解析为占位符。
你最初的写法中2个占位符放在字符串引号内,导致SQL仅识别到:id_client、:tarif、:date_actuelle 3个有效占位符,和你绑定的5个参数数量不匹配,因此抛出SQLSTATE[HY093]错误。
你后续调整的写法将占位符移到了引号外,PDO绑定字符串类型参数时会自动添加单引号,最终拼接后的内容就会带有多余的引号。

解决方案

推荐使用PHP层面拼接内容的方案,逻辑更清晰易维护:

// 先在PHP中拼接好完整的详情字段内容
$detail = "Renouvellement automatique annuel ({$dateRenou}) du compte {$compte_1['compte']}";

$sql_fact_1 = "INSERT INTO factures_interventions (id_client, id_facture, id_cat, detail_intervention, prix_intervention, date_intervention, etat_intervention)
VALUES (:id_client, '0', '3', :detail_intervention, :tarif, :date_actuelle, '0' )";

$req = $bdd->prepare($sql_fact_1);

$req->bindParam('id_client', $client_1['id'], PDO::PARAM_INT);
$req->bindParam('detail_intervention', $detail, PDO::PARAM_STR);
$req->bindParam('tarif', $resultat_form_1['tarif'], PDO::PARAM_STR);
$req->bindParam('date_actuelle', $date, PDO::PARAM_STR);

$req->execute();
$req->closeCursor();

如果需要在SQL层面完成字符串拼接,可以使用数据库自带的字符串拼接函数,以MySQL为例用CONCAT:

$sql_fact_1 = "INSERT INTO factures_interventions (id_client, id_facture, id_cat, detail_intervention, prix_intervention, date_intervention, etat_intervention)
VALUES (:id_client, '0', '3', CONCAT('Renouvellement automatique annuel (', :date_fin, ') du compte ', :compte), :tarif, :date_actuelle, '0' )";

$req = $bdd->prepare($sql_fact_1);

$req->bindParam('id_client', $client_1['id'], PDO::PARAM_INT);
$req->bindParam('date_fin', $dateRenou, PDO::PARAM_STR);
$req->bindParam('compte', $compte_1['compte'], PDO::PARAM_STR);
$req->bindParam('tarif', $resultat_form_1['tarif'], PDO::PARAM_STR);
$req->bindParam('date_actuelle', $date, PDO::PARAM_STR);

$req->execute();
$req->closeCursor();

两种方案最终存入数据库的内容都不会携带多余的单引号。

内容的提问来源于stack exchange,提问作者Mathieu Funfrock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:21:02