How to format long MySQL Insert-Statements

Advertisements

this might be a silly question, but I struggle with it a lot.

I usually have very long MySQL Insert statements which take many arguments. The arguments are all represented by question marks. Because of that, my code gets very confusing when I have to add more arguments in the middle. (EDIT: Can’t add all of the variables from the start, due to changing customer requirements)

$statement = $pdo->prepare("INSERT INTO table (Field1, Field2, Field3, Field4, Field5, Field6, ...) VALUES (?, ?, ?, 3, ?, ?, ...)");
$statement->execute([$x, $y, $z, $b, $c, ...]);

At the moment, I just count the question marks to find out where to add the variables. However, if you have 25 arguments, it takes a lot of time.

I didnt find good tips on google.
Very thankful for any help!

>Solution :

Well you could maintain an array of column names, and then auto generate the values clause:

$cols = ["col1", "col2", "col3"];
$values = "?" . str_repeat(", ?", count($cols) - 1);
$sql = "INSERT INTO table (" . implode(", ", $cols) . ") VALUES (" . $values . ")";
echo $sql;  // INSERT INTO table (col1, col2, col3) VALUES (?, ?, ?)

$statement = $pdo->prepare($sql);
$statement->execute([$x, $y, $z]);

Leave a ReplyCancel reply