Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 607
Samuel Reid Avatar asked Apr 17 '26 13:04

Samuel Reid


1 Answers

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.

like image 133
Rob W Avatar answered Apr 20 '26 01:04

Rob W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!