I’m attempting to cut down on the amount of PHP code needed to insert a lot of different $_POST data into a database. I’m currently using PDO with named params and listing them out manually every time. Perhaps there is a cleaner/better way than I’m attempting with my example, however, I’m in a position where I can’t refactor the 100’s of captured variables I already have listed like this:
$digital_fee = (isset ($_POST['digital_fee']) ? $_POST['digital_fee'] : '');
$banner_1 = (isset ($_POST['banner_1']) ? 1 : 0);
And the remaining PHP – SQL is written out like this:
$statement = $db->prepare("INSERT INTO $table
(digital_fee, banner_1)
VALUES
(:digital_fee, :banner_1)
ON DUPLICATE KEY UPDATE
digital_fee=:digital_fee, banner_1=:banner_1");
$statement->bindParam(':arn_mkt_stn', $arn_mkt_stn);
$statement->bindParam(':digital_fee', $digital_fee);
$statement->execute();
So I’m testing something like the below which I thought to turn into a Class/Function and call it passing in existing assoc arrays e.g. myFunction($db, $table, $arr_digital);
// example function to handle the PDO named params db inserts
$digital_fee ='500';
$banner_1 = '0';
$arr_digital = array("digital_fee"=>$digital_fee, "banner_1"=>$banner_1);
$table = 'myTable';
//create sql string with $vars
$sql = "INSERT INTO $table (";
foreach ($arr_digital as $key => $val){
$sql.= "$key, ";
}
$sql.= ") VALUES ( ";
foreach ($arr_digital as $key => $val){
$sql.= ":$key, ";
}
$sql.= ") ON DUPLICATE KEY UPDATE ";
foreach ($arr_digital as $key => $val){
$sql.= "$key=:$key, ";
}
echo $sql;
$statement = $db->prepare($sql);
$statement->bindParam(':arn_mkt_stn', $arn_mkt_stn);
foreach ($arr_digital as $key => $val){
$statement->bindParam(":$key, $val");
}
$statement->execute();
Running this returns an error which I think is format related (hopefully) – here’s the message,
Any pointers gratefully received and sorry this is a long post.
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
') VALUES ( '500', '0', ) ON DUPLICATE KEY UPDATE digital_fee='500', banner_1='0'' at line 1'
rich.
Try now .. should do fine not tested