Note that there are some explanatory texts on larger screens.

plurals
  1. POIn PHP, how does PDO protect from SQL injections? How do prepared statements work?
    text
    copied!<p>I understand the right way to protect a db from SQL injection is by using prepared statements. I would like to understand <strong>how</strong> prepared statements protect my db. </p> <p>For starters, are prepared statements the same thing as "parameterised queries"?</p> <p>As an example, I'm pasting below my code for the insertion of a new user in a user table. Is that secure? How does PDO work to make it secure? Does anything more needs to be done to secure the db from injection?</p> <p>In 'Class_DB.php':</p> <pre><code>class DB { private $dbHost; private $dbName; private $dbUser; private $dbPassword; function __construct($dbHost, $dbName, $dbUser, $dbPassword) { $this-&gt;dbHost=$dbHost; $this-&gt;dbName=$dbName; $this-&gt;dbUser=$dbUser; $this-&gt;dbPassword=$dbPassword; } function createConnexion() { return new PDO("mysql:host=$this-&gt;dbHost;dbName=$this-&gt;dbName", $this-&gt;dbUser, $this-&gt;dbPassword); } } </code></pre> <p>In 'DAO_User.php':</p> <pre><code>require_once('Class_DB.php'); class DAO_User { private $dbInstance; function __construct($dbInstance){ $this-&gt;dbInstance=$dbInstance; } function createUser($user){ $dbConnection=$this-&gt;dbInstance-&gt;createConnexion(); $query=$dbConnection-&gt;prepare("INSERT INTO users (userName, hashedPassword, userEmail) VALUES (?,?,?)"); $query-&gt;bindValue(1, $user-&gt;userName); $query-&gt;bindValue(2, $user-&gt;hashedPassword); $query-&gt;bindValue(3, $user-&gt;userEmail); $query-&gt;execute(); } } </code></pre> <p>Thanks,</p> <p>JDelage</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload