dongliao6777 2011-07-29 00:09
浏览 155
已采纳

如何在MySQL数据库中保存引号

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

  • 写回答

3条回答 默认 最新

  • douwei8911 2011-07-29 01:04
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在sql server里完成筛选
  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了