pdo 准备好的语句以无效参数号退出

pdo prepared statements exit with invalid parameter number

我有以下查询:

$sql="INSERT INTO form_6 SET 
      Project-name=:Project-name,
      Project-manager-gruppo-CDT=:Project-manager-gruppo-CDT,
      Short-description=:Short-description,
      Status=:Status,
      Dependency-with-BB-Pj=:Dependency-with-BB-Pj,
      Critical-issues=:Critical-issues"

和以下要插入的数据数组:

Array ( 
    [:Project-name] => test 
    [:Project-manager-gruppo-CDT] => jack 
    [:Short-description] => simple project 
    [:Status] => on going 
    [:Dependency-with-BB-Pj] => yes 
    [:Critical-issues] => problems trying to insert data
)

这是我用于 运行 查询的代码:

try{
    $stmt = $pdo->prepare($sql);
    $stmt->execute($values_array);
}
catch(PDOException $Exception){
    $message=$Exception->getMessage();
    $status=500;
    //ho avuto un problema e mi fermo
    die(json_encode(array('status'=>$status,'message' => $message)));
}

我真的不明白为什么会出现以下异常而终止:

Invalid parameter number: parameter was not defined

通常这是由于查询和数组之间的拼写错误或两次使用相同的占位符。但是排除了拼写错误,因为我使用 foreach:

一起构建了查询和数组
$values_array=array();
$sql = "INSERT INTO $tabella SET ";
foreach ($_POST as $key=>$value){
    $sql .= $key.'=:'.$key.',';
    $values_array[":$key"]=$value;
}
$sql=rtrim($sql,',');
echo $sql;  //this echoes the query at the beginning of the question
print_r($values_array);  //this echoes the array at the beginning of the question

我错过了什么?

您不能在参数名称中使用 -。当您编写 :Project-name 时,它等效于 :Profile - name,因此它需要一个名为 :Profile 的参数,然后尝试从中减去 name 列。

将占位符中的 - 替换为 _

此外,如果列名包含-,您需要将名称放在反引号中。参见 When to use single quotes, double quotes, and backticks in MySQL

$values_array=array();
$sql = "INSERT INTO $tabella SET ";
foreach ($_POST as $key=>$value){
    $placeholder = str_replace('-', '_', $key);
    $sql .= "`$key` = :$placeholder,";
    $values_array[":$placeholder"]=$value;
}