How to execute a PHP PDO prepared statement


Read {count} times since 2020

PDO – a method used to execute SQL statements risk free. Fast, secure and easy when compared to mysqli and mysql functions in PHP.
A lot of newbies including me heard about PDO mostly in the 2010 – 2013 years when a lot of sites got hacked of Mysql Injection. PDO is the easiest and safest way to execute an SQL code, complete risk free.
In this post I’m gonna tell you how to execute a prepared statement in PDO and the common mistakes made by programmers which results an error while executing SQL code.

How to execute a prepared statement ?

The following example shows how to execute an INSERT statement with the credentials {database_name:"db",host:"localhost",username:"root",password:"subins",table:"users",fields:"name,age,city"}.

$db = new PDO('mysql:dbname=<span style="color: red;">db</span>;host=<span style="color: red;"></span>', '<span style="color: red;">root</span>', '<span style="color: red;">subins</span>');
$sql=$db->prepare("INSERT INTO users (name,age,city) VALUES(?,?,?)");

Common mistakes

Now the common mistakes made while executing a code like above.

1. Some will put variables inside execute function instead of putting it in array like below:


   Right Way:


2. The other mistake is calling a function from $db instead of $sql like the following:

$sql=$db->prepare("INSERT INTO users (name,age,city) VALUES(?,?,?)");

   Right Way:

$sql=$db->prepare("INSERT INTO users (name,age,city) VALUES(?,?,?)");

Show Comments