PHP How to 100% prevent MySQL Injection

There are several ways to 100% prevent MySQL injection in PHP.

  • Using PDO
$id = $_GET["id"];

$query = $pdo->prepare('SELECT * FROM companies WHERE id = :id');

$query->execute([ 'id' => $id ]);

foreach ($query as $row) {
    // Use data in $row
}
  • Use MySQLi Extension (For MySQL)
$id = $_GET["id"];

$query = $dbConnection->prepare('SELECT * FROM companies WHERE id = ?');

$query->bind_param('s', $name); // 's' stands for variable type. Here it is String

$query->execute();

$result = $query->get_result();

while ($row = $result->fetch_assoc()) {
    // Use data in $row
}
  • MySQL Real Escape For Earlier PHP Versions (Deprecated in PHP5.5.0 | Removed in PHP 7 )
$id = $_GET["id"];
$safe_id = mysql_real_escape_string($id);

mysql_query("SELECT * FROM companies WHERE id =". $safe_id );

Leave a Reply

(*) Required, Your email will not be published