dreamice2013 2013-09-01 00:29
浏览 11
已采纳

PDO中的准备陈述; 比其他形式的SQL插入更受益?

I learned in school to do something like the below to insert data into SQL via $_POSTed form data.

$title = mysql_escape_string($_POST["newstitle"]);
$body = mysql_escape_string($_POST["newsbody"]);
$addnews = $db->query("
    INSERT INTO news
        VALUES (CURRENT_DATE, '$body', '$title', '')
");

However, it was fairly recently I was told I should be using the below instead:

$addnews = $db->prepare("
    INSERT INTO news
        VALUES (CURRENT_DATE, :body, :title, '')
");
$addnews->execute(array(
    ':body' => $_POST["newsbody"],
    ':title' => $_POST["newstitle"]));

What benefit does the second snippet of code offer? My professor in the aforementioned course was very traditional and I imagine was teaching an archaic way of doing things. He did use a lot of PDO, but never for the above example. And yes, I know mysql_escape_string() is deprecated, but that is how I was taught. I'm trying to make an effort to change my method to be more appropriate for current trends.

  • 写回答

1条回答 默认 最新

  • dqlk31541 2013-09-01 04:47
    关注

    Your question can be answered easily.

    I hope you understand that whatever value have to be properly formatted to be put into SQL query. So prepared statement does. Unlike whatever *_escape_string, which does only partial formatting, prepared statement intended to do the full one. And right where it have to be done - not sooner, not later - so it makes it impossible to forget. That's the point.

    You only need to understand the difference between formatting and escaping, which no professor ever understands.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误