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