Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to format long MySQL Insert-Statements

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading