2

我正在尝试学习 PDO 的基础知识。我已经构建了以下内容,将数据插入到我的表中,但我想获得有关这是否安全或是否可以做得更好的反馈?

我的帖子变量是否需要像您一样转义mysql_real_escape_string()

$firstname = $_POST['First_Name'];
$surname = $_POST['Surname'];
$nicknames = $_POST['Nicknames'];
$age = $_POST['Age'];


// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tsite_co_uk';
$userdb = 'access@site.co.uk';
$passdb = 'password';

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // Define an insert query
  $sql = "INSERT INTO `directory` 

  (`First_Name`,`Surname`,`Nicknames`,`Age`) 

  VALUES ('$firstname','$surname','$nicknames','$age')

  ";

  $count = $conn->exec($sql);

  $conn = null;        // Disconnect
}
catch(PDOException $e) {
  echo $e->getMessage();
}
4

1 回答 1

1

这不安全——您没有采取任何措施来防止用户提供的 $_POST 值进行 SQL 注入。您应该使用准备好的语句并将 vales 绑定到它们:

$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 $sql = "INSERT INTO `directory`  (`First_Name`,`Surname`,`Nicknames`,`Age`) 
     VALUES (:firstname ,:surname,:nicknames ,:age) ";

 $statement = $conn->prepare($sql);
 $statement->bindValue(":firstname", $firstname);
 $statement->bindValue(":surename", $surename);
 $statement->bindValue(":nicknames", $nicknames);
 $statement->bindValue(":age", $age);

 $count = $statement->execute();
于 2012-11-13T13:54:30.023 回答