I'm just starting out with PDO methods and now I'm stuck at a little question. If I create a form to insert first name and last name into a database I can insert all types of special characters with the code below:
try {
$db = new PDO('mysql:dbhost=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
$db -> exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
echo $e->getMessage();
}
$query = $db->prepare("INSERT INTO users(fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $fname,
":lname" => $lname
);
$query->execute($insert_array);
$db = NULL;
I can insert ":;,-!"#¤%&&(%)?{][]}£$€{{{$@@_--"
without any problems, even insert an SQL-injection. But when I try to update the database with a similar code it does accepts all types of special characters, except quotes. Why is that? The code I'm using to update is:
try {
$db = new PDO('mysql:dbhost=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
$db -> exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
echo $e->getMessage();
}
$query = $db->prepare("UPDATE users SET fname=:fname, lname=:lname WHERE userid=:userid");
$update_array = array(
":fname" => $fname,
":lname" => $lname,
":userid" => $_GET['userid']
);
$query->execute($update_array);
$db = NULL;
I'm grateful for all the help I can get.
-=SOLUTION=-
I had to use htmlspecialchars()
to "decode" the string. Like this:
<form action="" method="post">
First name<br><input type="text" name="fname" value="'.htmlspecialchars($user['fname']).'">
Last name: <br><input type="text" name="lname" value="'.htmlspecialchars($user['lname']).'">
<input type="submit">
</form>
Now all kinds of special characters works perfectly. Thanks for all help everybody, really appreciate it! :D