How to escape aphostrophes using PDO in PHP

Home > Search > How-to

When inserting or update data in a SQL database using PHP, single quotes or apostrophe's can cause problems.For example, inserting or updating the text I don't like mustard would only update or insert I don, because the apostrophe in don't would be interpreted as the end of the statement by SQL. 

This problem can be resolved by using a PDO prepared statement.

   $sql = "UPDATE table_name 
   SET column1= :column1, 
   column2 = :column2
   WHERE id = :id";
   $stmt = $con->prepare($sql); 
   $stmt->bindParam(':column1', $_POST['column1'], PDO::PARAM_STR); 
   $stmt->bindParam(':column2 ', $_POST['column2 '], PDO::PARAM_STR); 		
   $stmt->bindParam(':id', $_POST['id'], PDO::PARAM_INT); 		



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.