Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO with INSERT INTO through prepared statements [closed]

Tags:

sql

php

mysql

pdo

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!

like image 201
Bob Desaunois Avatar asked Sep 06 '13 10:09

Bob Desaunois


People also ask

What is PDO prepared statement?

In layman's terms, PDO prepared statements work like this: Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon preceding it for each value. Bind values or variables to the placeholders. Execute query simultaneously.

Is PDO safe from SQL injection?

The short answer is NO, PDO prepares will not defend you from all possible SQL-Injection attacks.

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

How do I select in PDO?

To select data from a table using PDO, you can use: The query() method of a PDO object. Or a prepared statement.


1 Answers

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([     '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 associative 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(['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.

like image 97
Novocaine Avatar answered Oct 16 '22 08:10

Novocaine