dtv55860 2014-03-20 21:06
浏览 46
已采纳

PDO准备了声明及其执行

I have recently 'upgraded' from MYSQL* to PDO, and I have a couple of related questions:

1/ I have a form on the webpage which submits alot of data. Rather than have 1 looong prepared statement with maybe 50 items in it, Id like to split it into maybe 5 separate statements:

//TODs
$stmt = $db->prepare("UPDATE first_page_data(tod_house, tod_bung, tod_flat, tod_barnc, tod_farm, tod_small, tod_build, tod_devland, tod_farmland) SET(?,?,?,?,?,?,?,?,?) WHERE email_address=?");

$stmt->bindValue(1, $_POST['tod_house'], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST['tod_bung'], PDO::PARAM_STR);
$stmt->bindValue(3, $_POST['tod_flat'], PDO::PARAM_STR);
$stmt->bindValue(4, $_POST['tod_barnc'], PDO::PARAM_INT);
$stmt->bindValue(5, $_POST['tod_farm'], PDO::PARAM_STR);
$stmt->bindValue(6, $_POST['tod_small'], PDO::PARAM_STR);
$stmt->bindValue(7, $_POST['tod_build'], PDO::PARAM_STR);
$stmt->bindValue(8, $_POST['tod_devland'], PDO::PARAM_STR);
$stmt->bindValue(9, $_POST['tod_farmland'], PDO::PARAM_STR);
$stmt->bindValue(10, $_SESSION['buyer_email']);
$stmt->execute();

This is the first of 5 blocks. If I didnt split it this statement would be 50 items long. My question is would there be any noticable adverse effects to splitting it up? Speed, pressure on the server, etc... as there would be 5 smaller updates to the database rather than 1 big one.

2/ My second question is quite simple - is the code above considered 'safe'? Ive seen people put the $_POST values into a variable (mostly because of MYSQL) and then into the statements. Ive read that using PDO prevents any injections and so the POST values can be put straight into bindValue but im not entirely sure!

  • 写回答

1条回答 默认 最新

  • duanhanglekr37902 2014-03-20 21:20
    关注

    Yes, it's safe (PDO::prepare takes care of that), and one big statement is more efficient that a series of smaller ones. But you can script your code to make it less painful to read and edit. Suggestions:

    1. Put the query in a string and make it more vertical, one line per parameter. Heredoc syntax is great for this and avoids concatenation.

    2. Use :whatever in the query instead of the numbered values, just for clarity and portability.

    3. Instead of calling bindValue repeatedly, you could build an array and then pass it whole to execute(); Arrays are the simplest thing PHP can do, and should be less overhead than calling bindValue repeatedly, though the real difference is probably negligible.

      $arrParams[] = array(':tod_house' => $_POST["tod_house"];

      $stmt->execute($arrParams);

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

报告相同问题?

悬赏问题

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