I have a problem in a php script where I am using PDO to access my database. I can't seem to get PDO to escape my string when I use prepare()
or execute()
in PDO. I've looked all over and I haven't found an answer to this problem because everywhere I look it says PDO automatically escapes the strings.
Here's my code :
$statement = $db->prepare("INSERT INTO Table (ID, Column1, Column2) VALUES (NULL, '$var1', '$var2')");
$query->execute();
Let's admit $var1 = "abc'def"
and $var2 = "123"
The problem is I get an error message because the quote wasn't escaped.
Error : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'def', '123')' at line 1
I've also tried using the query()
method but same prpblem with the quotes.
I really don't understand and it's frustrating. Thanks for any help.
Try this:
# Took out ID, as it should be auto_increment and handled by database
$statement = $db->prepare("INSERT INTO Table (Column1, Column2) VALUES (:col1, :col2)");
$statement->bindValue(':col1', $var1, PDO::PARAM_STR);
$statement->bindValue(':col2', $var2, PDO::PARAM_INT);
$statement->execute();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With