简体   繁体   中英

Insert All Post Data into MySQL Database

The following topic is close to what I'm trying to ask, but it's outdated considering the mysql functions are deprecated in php now and there are prepared statements for preventing sql injection. insert all $_POST data into mysql using PHP?

Basically, I have a huge number of columns in my database that all need to get filled up when I submit this form. The form matches each column with an input field of the same name (the name attribute on the input field is the same as the column name it belongs in. So $_POST['firstName'] goes in the firstName column, and so on).

Is there a way using mysqli or PDO that I could easily just take all my POST data and automatically insert it into the MySQL table without going through each field by hand? I could code them all out using prepared statements, but there are a ton of columns and I'd like to get them done all at once if possible.

This is the beginning of the long version I don't really want to have to complete.

$stmt = $connection->prepare("INSERT INTO area_retreat 
(user,firstName,lastName,...etc) 
VALUES 
(?,?,?,...etc)
ON DUPLICATE KEY UPDATE 
user=VALUES(user),
firstName=VALUES(firstName),
lastName=VALUES(lastName),
...etc
");
$stmt->bind_param("sss",
    $username,
    $_POST['firstName'],
    $_POST['lastName']
 );

$stmt->execute();

INSERT INTO area_retreat VALUES (?, ?, ...) -- however, you have to match ALL columns as shown in the database.

If you have an auto increment ID, you will need to provide NULL for that column in the proper column order.

To avoid errors you definitely need to store the list of variables one way or another. It could be as simple as an array:

$fields = array('firstName', etc.);

Then you can loop through your array to generate your sql statement dynamically and using named placeholders instead of question marks, you only need to bind them once. You can also store the values in an array and send that array as a parameter to execute() :

// start of query
$values = array();
$query = '...';
foreach ($fields as $field)
{
  if (isset($_POST[$field]))
  {
    // add to query
    $query .= "...";
    // add value to array so that you can feed the array to `execute`
    $values[':' . $field] = $_POST[$field];
  }
}
// add end of query
$query .= '...';

$stmt->execute($values);

If you want to use the same variables in an ON DUPLICATE KEY UPDATE section, you can do another loop or build an insert section that you can use twice after looping once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM