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 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding