PDO Do Not Avoid String Quotes

I have a problem in a PHP script where I use PDO to access my database. I cannot get PDO to escape my line when I use prepare() or execute() in PDO. I looked through everything, and I could not find an answer to this problem, because wherever I look, it says that PDO automatically eludes lines. Here is my code:

 $statement = $db->prepare("INSERT INTO Table (ID, Column1, Column2) VALUES (NULL, '$var1', '$var2')"); $query->execute(); 

Let $var1 = "abc'def" and $var2 = "123" be allowed $var2 = "123" The problem is that I get an error message because the quote was not escaped.

Error: SQLSTATE [42000]: syntax error or access violation: 1064 You have an error in the SQL syntax; check the manual that matches your version of MySQL server for the correct syntax to use next to "def", '123') 'on line 1

I also tried using the query() method, but the same prpblem with quotes. I really do not understand, and it is frustrating. Thanks for any help.

+4
source share
3 answers

Try the following:

 # 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(); 
+13
source

Refer to the bindParam () method of the PDO library.

This makes your request look like this:

 $statement = $db->prepare("INSERT INTO Table (ID, Column1, Column2) VALUES (NULL, ?, ?)"); $statement->bindParam(1, $var1, PDO::PARAM_STR); $statement->bindParam(2, $var2, PDO::PARAM_INT); $query->execute(); 

// I really have to upload new answers :) When the bar says there is.

+2
source

There is a function for this purpose. Take a look at www.php.net/addslashes

0
source

Source: https://habr.com/ru/post/1401053/


All Articles