Bob Desaunois Bob Desaunois - 6 months ago 14
MySQL Question

PDO with INSERT INTO through prepared statements

On my adventure through the jungles of PHP: Data Objects I've encountered a problem with executing MySQL queries through prepared statements.

Observe the following code:

$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('Bob','Desaunois','18')");

$statement->execute();


This is me, and I want to be in my database.
However I keep getting lost in.. well.. I don't know!
According to google this is the way to do it, though my database stays empty.

Am I missing something here? because I've been stuck for a good hour now and would like to continue studying PDO!

Sorry in advance if this is a stupid question, I'm just really stuck here.

Answer

You should be using it 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(array(
    "fname" => "Bob",
    "sname" => "Desaunois",
    "age" => "18"
));

Prepared statements are 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 array of the variables you defined in the SQL statement.

You may also 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(array("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.