mysql - Comment puis-je empêcher l'injection SQL en PHP

Mots clés : phpmysqlsecuritysql-injectionphp

meilleur 4 Réponses mysql - Comment puis-je empêcher l'injection SQL en PHP

vote vote

93

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');   $stmt->execute([ 'name' => $name ]);   foreach ($stmt as $row) {      // Do something with $row  } 
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');  $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'   $stmt->execute();   $result = $stmt->get_result();  while ($row = $result->fetch_assoc()) {      // Do something with $row  } 
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');  $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');  $preparedStatement->execute([ 'column' => $unsafeValue ]); 
// Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC') {    $dir = 'ASC'; } 
vote vote

90

//Connect  $unsafe_variable = $_POST["user-input"]; $safe_variable = mysql_real_escape_string($unsafe_variable);  mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");  //Disconnect 
<?php     $mysqli = new mysqli("server", "username", "password", "database_name");      // TODO - Check that connection was successful.      $unsafe_variable = $_POST["user-input"];      $stmt = $mysqli->prepare("INSERT INTO table (column) VALUES (?)");      // TODO check that $stmt creation succeeded      // "s" means the database expects a string     $stmt->bind_param("s", $unsafe_variable);      $stmt->execute();      $stmt->close();      $mysqli->close(); ?> 
vote vote

73

$orders  = array("name", "price", "qty"); // Field names $key = array_search($_GET['sort'], $orders)); // if we have such a name $orderby = $orders[$key]; // If not, first one will be set automatically.  $query = "SELECT * FROM `table` ORDER BY $orderby"; // Value is safe 
$orderby = white_list($_GET['orderby'], "name", ["name","price","qty"], "Invalid field name"); $query  = "SELECT * FROM `table` ORDER BY `$orderby`"; // sound and safe 
vote vote

65

$stmt = $conn->prepare("INSERT INTO tbl VALUES(:id, :name)"); $stmt->bindValue(':id', $id); $stmt->bindValue(':name', $name); $stmt->execute(); 

Questions similaires