PHP with the PDO module installed

PHP PDO insert boilerplate code

By Erik Thiart | erikthiart | 25 Nov 2020


If you are like me you often grab some old code and copy it and then just change the values a bit.

I find myself more often than not googling the code on StackOverflow in order to get some examples because I am too lazy to type it out.

Here is the code I use for PDO inserts in PHP

$stmt = $pdo->prepare('INSERT INTO table_name (column_name, column_name, column_name) VALUES (:column_name, :column_name, :column_name)');
$stmt->bindParam(':column_name', $column_name);
$stmt->bindParam(':column_name', $column_name);
$stmt->bindParam(':column_name', $column_name);
$stmt->execute();

OR if you use the POSTed variables directly instead.

$stmt = $pdo->prepare('INSERT INTO table_name (column_name, column_name, column_name) VALUES (:column_name, :column_name, :column_name)');
$stmt->bindParam(':column_name', $_POST['column_name']);
$stmt->bindParam(':column_name', $_POST['column_name']);
$stmt->bindParam(':column_name', $_POST['column_name']);
$stmt->execute();

I really hope this boilerplate code is useful to you.

Let me know if you need any other quick-grab examples.

How do you rate this article?

2


Erik Thiart
Erik Thiart

erikthiart.com


erikthiart
erikthiart

I mainly focus on writing short tutorials and cheat sheets for programmers. However, you might find some personal finance and even small life hacks in between as well. If you want a topic covered then follow me on Twitter and send your requests through, it is @erikthiart on there.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.