Hello PHP freaks
I'm a newbie so bear with me.
I have a generic problem and I'm sure code already exists to solve it. I need to have a dynamic sql string variable that will only produce an insert statement with database column names corresponding to input fields on the form that contain values, ignoring the blank ones. I know some looping function like foreach might be used, but if I use it on the $_POST array I'll get the values, not the keys.
(the first field, well_no, is a primary key and is held in a session variable, so I know I'll be inserting a value for that column)
$ins = "well_no,";
foreach($_POST as $field)
if (!empty($field)){
$ins .=$_POST[$field].",";
}
And I get a warning
"Warning: Undefined array key "production in... Here "production" is actually a form input.
the problem is my insert statement is hard-coded:
$sql = "INSERT INTO well_parent (well_no, easting, northing, purpose, country, admin1, admin2, admin3, settlement,
orig_wellno, date_completed, coord_sys, elev, status)
VALUES (:well_no, :easting, :northing, ...
How can I adjust the sql statement and also the $data array holding the variables. Here's the context:
$sql = "INSERT INTO well_parent (well_no, easting, northing, purpose, country, admin1, admin2, admin3, settlement,
orig_wellno, date_completed, coord_sys, elev, status)
VALUES (:well_no, :easting, :northing, :purpose, :country, :admin1, :admin2, :admin3, :settlement, :orig_wellno, :date_completed,
:coord_sys, :elev, :status)";
$stmnt = $pdo->prepare($sql);
$data = [':well_no'=>$well_no, ':easting'=>$easting, ':northing'=>$northing, ':purpose'=>$purpose, ':country'=>$country,
':admin1'=>$admin1, ':admin2'=> $admin2, ':admin3'=>$admin3, ':settlement'=>$settlement, ':orig_wellno'=>$orig_wellno,
':date_completed'=> $date_completed, ':coord_sys'=> $coord_sys, ':elev'=>$elev, ':status'=>$status];
$stmnt->execute($data);