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!
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.
The short answer is NO, PDO prepares will not defend you from all possible SQL-Injection attacks.
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
To select data from a table using PDO, you can use: The query() method of a PDO object. Or a prepared statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With