"how can i prevent sql injection in php?" Code Answer


use prepared statements and parameterized queries. 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.

you basically have two options to achieve this:

  1. using pdo (for any supported database driver):

    $stmt = $pdo->prepare('select * from employees where name = :name');
    $stmt->execute([ 'name' => $name ]);
    foreach ($stmt as $row) {
        // do something with $row
  2. using mysqli (for mysql):

    $stmt = $dbconnection->prepare('select * from employees where name = ?');
    $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row

if you're connecting to a database other than mysql, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for postgresql). pdo is the universal option.

correctly setting up the connection

note that when using pdo to access a mysql database real prepared statements are not used by default. to fix this you have to disable the emulation of prepared statements. an example of creating a connection using pdo is:

$dbconnection = new pdo('mysql:dbname=dbtest;host=;charset=utf8', 'user', 'password');

$dbconnection->setattribute(pdo::attr_emulate_prepares, false);
$dbconnection->setattribute(pdo::attr_errmode, pdo::errmode_exception);

in the above example the error mode isn't strictly necessary, but it is advised to add it. this way the script will not stop with a fatal error when something goes wrong. and it gives the developer the chance to catch any error(s) which are thrown as pdoexceptions.

what is mandatory, however, is the first setattribute() line, which tells pdo to disable emulated prepared statements and use real 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).

although you can set the charset in the options of the constructor, it's important to note that 'older' versions of php (before 5.3.6) silently ignored the charset parameter in the dsn.


the sql statement you pass to prepare is parsed and compiled by the database server. by specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. then when you call execute, the prepared statement is combined with the parameter values you specify.

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 $name variable contains 'sarah'; delete from employees the result would simply be a search for the string "'sarah'; delete from employees", and you will not end up with an empty table.

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.

oh, and since you asked about how to do it for an insert, here's an example (using pdo):

$preparedstatement = $db->prepare('insert into table (column) values (:column)');

$preparedstatement->execute([ 'column' => $unsafevalue ]);

can prepared statements be used for dynamic queries?

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.

for these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// value whitelist
// $dir can only be 'desc', otherwise it will be 'asc'
if (empty($dir) || $dir !== 'desc') {
   $dir = 'asc';
By w3stack on January 21 2022
include 'dbconnection.php';
$userid = $_POST['userid'];
$password = $_POST['password'];
$sanitized_userid = 
    mysqli_real_escape_string($db, $userid);
$sanitized_password = 
    mysqli_real_escape_string($db, $password);
$sql = "SELECT * FROM users WHERE username = '" 
    . $sanitized_userid . "' AND password = '" 
    . $sanitized_password . "'";
$result = mysqli_query($db, $sql) 
    or die(mysqli_error($db));
$num = mysqli_fetch_array($result);
if($num > 0) {
    echo "Login Success";
else {
    echo "Wrong User id or password";
By atiretoo on October 27 2022
       * Before executing, prepare statements by binding parameters.
       * Bind validated user input (in this case, the value of $id) to the
       * SQL statement before sending it to the database server.
       * This fixes the SQL injection vulnerability.
      $q = "SELECT username 
          FROM users
          WHERE id = :id";
      // Prepare the SQL query string.
      $sth = $dbh->prepare($q);
      // Bind parameters to statement variables.
      $sth->bindParam(':id', $id);
      // Execute statement.
      // Set fetch mode to FETCH_ASSOC to return an array indexed by column name.
      // Fetch result.
      $result = $sth->fetchColumn();
       * HTML encode our result using htmlentities() to prevent stored XSS and print the
       * result to the page
      print( htmlentities($result) );
      //Close the connection to the database.
      $dbh = null;
    catch(PDOException $e){
       * You can log PDO exceptions to PHP's system logger, using the
       * log engine of the operating system
       * For more logging options visit http://php.net/manual/en/function.error-log.php
      error_log('PDOException - ' . $e->getMessage(), 0);
       * Stop executing, return an Internal Server Error HTTP status code (500),
       * and display an error
      die('Error establishing connection with database');
   } else{
     * If the value of the 'id' GET parameter is not numeric, stop executing, return
     * a 'Bad request' HTTP status code (400), and display an error
    die('Error processing bad or malformed request');
By James Durand on October 27 2022

Answers related to “how can i prevent sql injection in php?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.