Bob Desaunois Bob Desaunois - 1 year ago 68
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)


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 Source

You should be using it like so

$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)");
    "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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download