I'm trying to learn the fundamentals of PDO. I've built the following that inserts data into my table but I would like to get feedback on whether or not this is secure or whether it could have been done better?
Would my post variables need to be escaped like you would with 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();
}