0

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.

3
  • 1
    foreach($_POST as $field => $value) { $fldArray[$field] = $mysqli->escape_string($value); } - However, a better way to do this is to drop escape_string() ENTIRELY and using prepared statements with binded parameters. Commented Dec 7, 2018 at 19:21
  • Don't escape. Bind parameters instead! Commented Dec 7, 2018 at 19:22
  • Thanks for your suggestion. I've corrected my syntax per your input. Thanks very much. I will explore binding parms as well. Commented Dec 7, 2018 at 20:54

1 Answer 1

0

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); 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.