You should using it looks like so :
<?php $dbhost = 'localhost'; $dbname = 'pdo'; $dbusername = 'root'; $dbpassword = '845625'; $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword); $statement = $link->prepare('INSERT INTO testtable (name, lastname, age) VALUES (:fname, :sname, :age)'); $statement->execute([ 'fname' => 'Bob', 'sname' => 'Desaunois', 'age' => '18', ]);
Prepared statement is used to sanitize your input, and to do that you can use
:foo without any single quotes within the SQL to bind variables, and then in the
execute() function you pass in an associative array of the variables you defined in the SQL statement.
You may use
? instead of
:foo and then pass in an array of just the values to input like so;
$statement = $link->prepare('INSERT INTO testtable (name, lastname, age) VALUES (?, ?, ?)'); $statement->execute(['Bob', 'Desaunois', '18']);
Both ways have their advantages and disadvantages. I personally prefer to bind the parameter names as it's easier for me to read.