doujichan1399 2018-09-26 18:17
浏览 84
已采纳

循环中的PDO查询

I have this code:

$sql = "SELECT id FROM videos";
$stmp = $db->prepare($sql);
$stmp->execute();
while ($row = $stmp->fetchAll(PDO::FETCH_ASSOC)) {

    $vkey = md5($row['id'] . "video");

    $sql = "UPDATE videos SET vkey = :vkey WHERE id = :id";
    $stmp = $db->prepare($sql);
    $stmp->execute(array(
        ":vkey" => $vkey,
        ":id"   => $row['id']
    ));

}

Why is execute only for the first id from the first select and not for all it's in the loop?

  • 写回答

1条回答 默认 最新

  • dongyue6199 2018-09-26 18:31
    关注

    You could completely avoid all of that code by just doing this:

    $db->query("UPDATE videos SET vkey = MD5(CONCAT(vkey, 'video'))");
    

    (Or you could do this query in your backend like PHPMyAdmin UPDATE videos SET vkey = MD5(CONCAT(vkey, 'video')))


    However, if you for some reason want to loop through your database, you could do this:

    $sql = "SELECT id FROM videos";
    
    //no reason to use prepare() because you aren't passing variables.
    $stmp = $db->query($sql);
    $stmp->execute();
    $results = $stmp->fetchAll(PDO::FETCH_ASSOC);
    
    //prepare UPDATE query outside of loop, this way you don't send 2 requests to your database for every row
    $stmp = $db->prepare("UPDATE videos SET vkey = :vkey WHERE id = :id");
    
    foreach($results as $result) {
        $vkey = md5($result['id']."video");
        $stmp->execute(
            array(
                ":vkey" => $vkey, 
                ":id" => $result['id']
            )
        );
    }
    

    Also, it's usually a good idea to check the return values inside the loop to make sure there were no errors, you could probably do this by using something like $stmp->rowCount() to check if there were any rows effected.

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

报告相同问题?

悬赏问题

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