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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度