Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Use prepared statements and parameterized queries.</strong> These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.</p> <p>You basically have two options to achieve this:</p> <ol> <li><p>Using <a href="http://php.net/manual/en/book.pdo.php" rel="noreferrer">PDO</a> (for any supported database driver):</p> <pre class="lang-php prettyprint-override"><code>$stmt = $pdo-&gt;prepare('SELECT * FROM employees WHERE name = :name'); $stmt-&gt;execute(array('name' =&gt; $name)); foreach ($stmt as $row) { // do something with $row } </code></pre></li> <li><p>Using <a href="http://php.net/manual/en/book.mysqli.php" rel="noreferrer">MySQLi</a> (for MySQL):</p> <pre class="lang-php prettyprint-override"><code>$stmt = $dbConnection-&gt;prepare('SELECT * FROM employees WHERE name = ?'); $stmt-&gt;bind_param('s', $name); // 's' specifies the variable type =&gt; 'string' $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); while ($row = $result-&gt;fetch_assoc()) { // do something with $row } </code></pre></li> </ol> <p>If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (e.g. <code>pg_prepare()</code> and <code>pg_execute()</code> for PostgreSQL). PDO is the universal option.</p> <h2>Correctly setting up the connection</h2> <p>Note that when using <code>PDO</code> to access a MySQL database <em>real</em> prepared statements are <strong>not used by default</strong>. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:</p> <pre class="lang-php prettyprint-override"><code>$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass'); $dbConnection-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); </code></pre> <p>In the above example the error mode isn't strictly necessary, <strong>but it is advised to add it</strong>. This way the script will not stop with a <code>Fatal Error</code> when something goes wrong. And it gives the developer the chance to <code>catch</code> any error(s) which are <code>throw</code>n as <code>PDOException</code>s.</p> <p>What is <strong>mandatory</strong>, however, is the first <code>setAttribute()</code> line, which tells PDO to disable emulated prepared statements and use <em>real</em> prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).</p> <p>Although you can set the <code>charset</code> in the options of the constructor, it's important to note that 'older' versions of PHP (&lt; 5.3.6) <a href="http://php.net/manual/en/ref.pdo-mysql.connection.php" rel="noreferrer">silently ignored the charset parameter</a> in the DSN.</p> <h2>Explanation</h2> <p>What happens is that the SQL statement you pass to <code>prepare</code> is parsed and compiled by the database server. By specifying parameters (either a <code>?</code> or a named parameter like <code>:name</code> in the example above) you tell the database engine where you want to filter on. Then when you call <code>execute</code>, the prepared statement is combined with the parameter values you specify. </p> <p>The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the <code>$name</code> variable contains <code>'Sarah'; DELETE FROM employees</code> the result would simply be a search for the string <code>"'Sarah'; DELETE FROM employees"</code>, and you will not end up with <a href="http://xkcd.com/327/" rel="noreferrer">an empty table</a>.</p> <p>Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.</p> <p>Oh, and since you asked about how to do it for an insert, here's an example (using PDO):</p> <pre class="lang-php prettyprint-override"><code>$preparedStatement = $db-&gt;prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement-&gt;execute(array('column' =&gt; $unsafeValue)); </code></pre> <h2>Can prepared statements be used for dynamic queries?</h2> <p>While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.</p> <p>For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.</p> <pre><code>// Value whitelist // $dir can only be 'DESC' otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC') { $dir = 'ASC'; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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