安全的表数据条目PHP / PDO / MySQL

时间:2012-11-13 13:48:59

标签: php mysql pdo

我正在努力学习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();
}

1 个答案:

答案 0 :(得分: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();