dops57958 2015-03-26 16:34 采纳率: 0%
浏览 39
已采纳

使用PDO通过PHP保存到mysql时,字符串会发生变异

This is the sql:

INSERT INTO stepup (target, body) VALUES ('http://test.com/dev-ws/events', '{"username":"Unknown","verb":"answer","object":"http:\/\/localhost\/elgg\/answers\/view\/42954\/q1","context":{"course":"42902","phase":"1","widget_type":"questions","activity_id":"95c48","widget_title":"Wonder moment"},"originalrequest":{"value":{"description":"<p>\u041f\u0440\u043e\u0443\u0447\u0432\u0430\u043d\u0435<\/p>","question_id":42954}},"starttime":"2015-03-26 17:28:57 +0100","endtime":"2015-03-26 17:28:57 +0100"}')

then I do $conn->exec($sql);

but the actual content of body in the DB (mysql) is:

"{\"username\":\"Unknown\",\"verb\":\"answer\",\"object\":\"http://localhost/elgg/answers/view/42954/q1\",\"context\":{\"course\":\"42902\",\"phase\":\"1\",\"widget_type\":\"questions\",\"activity_id\":\"95c48\",\"widget_title\":\"Wonder moment\"},\"originalrequest\":{\"value\":{\"description\":\"<p>u041fu0440u043eu0443u0447u0432u0430u043du0435</p>\",\"question_id\":42954}},\"starttime\":\"2015-03-26 17:28:57 +0100\",\"endtime\":\"2015-03-26 17:28:57 +0100\"}"

So \u is replaced by u :(

What can I do.. I thought that by not "preparing" the SQL, this will stop happening...

  • 写回答

3条回答 默认 最新

  • dongmeng1868 2015-03-26 18:30
    关注

    It seems like you are injecting JSON content into an SQL string literal in a query. You probably have SQL-injection security holes, which is a worse problem than \u sequences going missing.

    You should use parameterised queries to avoid having to think about escaping rules. For example in PDO:

    $url= 'http://test.com/dev-ws/events';
    $json= '{"username":"Unknown","verb":"answer","object":"http://localhost/elgg/answers/view/42954/q1","context":{"course":"42902","phase":"1","widget_type":"questions","activity_id":"95c48","widget_title":"Wonder moment"},"originalrequest":{"value":{"description":"<p>\u041f\u0440\u043e\u0443\u0447\u0432\u0430\u043d\u0435</p>","question_id":42954}},"starttime":"2015-03-26 17:28:57 +0100","endtime":"2015-03-26 17:28:57 +0100"}';
    
    $q= $db->prepare('INSERT INTO stepup (target, body) VALUES (?, ?)');
    $q->bindParam(1, $url, PDO::PARAM_STR);
    $q->bindParam(2, $json, PDO::PARAM_STR);
    $q->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?