I have the following query:
$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"
and the following array of data to be inserted:
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
)
and this is the code that I am using to run the query:
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)));
}
I really am not able to see why this terminates with the following exception:
Invalid parameter number: parameter was not defined
usually this comes from typos between the query and the array or using the same placeholder two times. But typos are excluded since I build the query and the array together using a 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
What am I missing?
You can't use -
in parameter names. When you write :Project-name
it's equivalent to :Profile - name
, so it's expecting a parameter named :Profile
, and then trying to subtract the column name
from that.
Replace the -
with _
in the placeholder.
Also, if a column name contains -
, you need to put the name in backticks. See 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;
}