How to prevent SQL injection in PHP using PDO and MySQLi? | #MySQL #MySQLTips


Updated July 19, 2013 ● 1,153 views

SQL injection in PHP is one of the most common vulnerabilities in web applications. Let me show you how you can prevent SQL injection on your website using PDO and MySQLi.

 

Using PDO:

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

Using MySQLi:

$name = $_GET['username'];
$password = $_GET['password'];
 
if ($stmt = $mysqli->prepare("INSERT INTO tbl_users (name, password) VALUES (?, ?)")) {
    // Bind the variables to the parameter as strings. 
    $stmt->bind_param("ss", $name, $password);
    // Execute the statement.
    $stmt->execute();
    // Close the prepared statement.
    $stmt->close();
}

0 Comments


This website uses cookies. By continuing to use this site, you are accepting our Privacy Policy and Terms of Service.