Search code examples
phpmysqlutf-8pdoquotes

How to save quotes in MySQL database


Whenever I add a single quote (') or a double quote (") in my PHP formfield, it will be saved in my MySQL DB as " / '. How can save the 'real' "quotes" in my DB?

I tried to prevent this by making a secure Mysql connection thru PDO, but it doesn't seem to work properly.

So here's the important part of my code:

    $insert_hello = filter_var($_POST['hello'], FILTER_SANITIZE_STRING);
    $dbh->query("SET NAMES 'utf8'");
    $stmt = $dbh->prepare("INSERT INTO testtable (data) VALUES (:hello)");
    $stmt->bindParam(':hello', $insert_hello, PDO::PARAM_STR);      
    $stmt->execute();

Some background information:

The server runs on PHP v5.2.12-0.

The DBStorage engine is InnoDB and has its client-, connection-, results- and system charset are set to utf8.

The DB field has its collation set to utf8_unicode_ci.

Magic quotes are disabled thru .htaccess.

Thanks in advance!

Kind regards, Jroen


Solution

  • Ok, just to formalize the correct answer:

    The problem is caused by filter_var() that converts some characters into HTML entities. There is no need to manually sanitize the data since PDO does that for you.

    You can just write something like this, that should work just fine:

    $dbh->query("SET NAMES 'utf8'");
    $stmt = $dbh->prepare("INSERT INTO testtable (data) VALUES (:hello)");
    $stmt->bindParam(':hello', $_POST['hello'], PDO::PARAM_STR);      
    $stmt->execute();