I' am really confused with PDO Prepared Statement. I did everything as it says on php.net documentation. When I inserted JavaScript into the database and then query the database and output the results on the page, it gave me JavaScript alert which was on the database.
Does PDO protect user data from this type of attacks or do we have to do our own sanitizing and escaping or is it am missing something here.
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=test', "root", "");
} catch ( PDOException $e ) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$query = $db->query('SELECT * from users');
if( $query->rowCount() ){
$rows = $query->fetchAll( PDO::FETCH_OBJ);
foreach( $rows as $row ){
echo $row->user_name;
echo "<br/>";
}
} else {
echo "No results found";
}
$user_name = "<script type=\"text/javascript\">alert(\"Works\");</script>";
$user_email = "example@gmail.com";
$user_password = "password";
$user_status = "1";
$data = array(
":user_name" => $user_name,
":user_email" => $user_email,
":user_password" => $user_password,
":user_status" => $user_status
);
$sql = "INSERT INTO users (user_name, user_email, user_password, user_status) VALUES(:user_name, :user_email, :user_password, :user_status)";
$prepare = $db->prepare($sql);
$exec = $prepare->execute($data);
?>