I have code that generalizes building the SQL string to insert a record into a table by (1) setting the 'name' of the form element to be the same as the table column to which it corresponds, and (2) building an array of field name => value pairs. I do it like this:
$fldArray = array();
foreach($_POST as $field => $value) {
$fldArray[$field] = $value; //create a field => value array
}
This allows me to build the SQL statement easily like this:
$visit_SQL = "INSERT INTO visits (";
foreach ($fldArray as $key => $value) {
$flds .= ($key) . ", " ; // sets up all the field names.
I then do something similar to generate the 'VALUES' part of the SQL statement. I then need only to add the provider_id info
$visit_SQL = $visit_SQL . "provider_id, " . $flds . ") VALUES (" . $user_ID . ", " . $vals . ")";
The reason I go about it this way is that there are a large number of Yes/No checkboxes on the form so it saves typing errors etc.
This works well except for two text inputs that require "$mysqli->escape_string(['field_name']) to deal with apostrophes etc. before inserting into the database. I proved that the following works for explicit field names,
$test = $mysqli->escape_string($_POST['visit_notes']);
print_r($test) ;
However, I cannot generalize it into this statement (from above):
foreach($_POST as $field => $mysqli->escape_string($_POST[$value])) {
$fldArray[$field] = $value;
}
I'd appreciate knowing if I have a syntax error or if what I'm seeking is not possible. Thanks in advance for any helpful responses.
You don't put the function call in the foreach
header, you do it in the body.
foreach($_POST as $field => $value) {
$fldArray[$field] = $mysqli->escape_string($value);
}