Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Not escaping string quotes

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.

like image 922
califrench Avatar asked Dec 06 '22 15:12

califrench


1 Answers

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();
like image 72
Mike Purcell Avatar answered Dec 14 '22 22:12

Mike Purcell