doujichan1399 2018-09-26 10: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 10: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部