Escaping single quote and save to database with quote

Issue

How do I escape single quote for example.

User enters in the name field: El’art Devoun

$myvar = $data['name']; //name is El'art Devoun
// some code to remove the single quote

Then save it to database with data not escaped?

Solution

Use PDO and parameterized queries for you database insert. This will automatically prevent sql injection etc from the quote (and other non-safe entities):

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

$stmt = $dbh->prepare("INSERT INTO yourTable (name) VALUES (:name)");
$stmt->bindParam(':name', $name);

// insert row
$name = $data['name'];
$stmt->execute();

?>

more can be found in the php docs

Answered By – Tims

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published