Blake Connally
Blake Connally

Reputation: 689

PDO SQL - Inserting dozens of fields

Currently I have a page with a form with over 25+ fields, all posting to a single file that grabs the posts and stores them in a SQL database. I've found it extremely inefficient to assign variables to each post value, there has to be an eaiser solution.

Here is my example:

/*Post Data*/
$val_1 = $_POST['val_1'];
$val_2 = $_POST['val_2'];
$val_3 = $_POST['val_3'];

$query = $handler->prepare("INSERT INTO `database` (col_1, col_2, col_3) VALUES (:val_1, :val_2, :val_3)");
$query->execute([
    ':val_1'    => $val_1,
    ':val_2'    => $val_2,
    ':val_3'    => $val_3
]);

I feel like there has to be a way to accomplish this with a loop of some sort so that my queries aren't ridiculously long and messy like this would be.

Upvotes: 0

Views: 36

Answers (1)

u_mulder
u_mulder

Reputation: 54841

In a simple way:

$query = $handler->prepare("INSERT INTO `database` (col_1, col_2, col_3) VALUES (?, ?, ?)");
$query->execute($_POST);

With str_repeat you can repeat symbols as many times as you need, e.g:

$times = 20; // or sizeof($_POST);
$str = str_repeat('?,', $times);
$str = rtrim($str, ',');    // remove last `,`

Upvotes: 2

Related Questions