PHP PDO with foreach and fetch

后端 未结 4 1929
我在风中等你
我在风中等你 2020-12-01 16:31

The following code:



        
4条回答
  •  借酒劲吻你
    2020-12-01 16:39

    foreach over a statement is just a syntax sugar for the regular one-way fetch() loop. If you want to loop over your data more than once, select it as a regular array first

    $sql = "SELECT * FROM users";
    $stm = $dbh->query($sql);
    // here you go:
    $users = $stm->fetchAll();
    
    foreach ($users as $row) {
        print $row["name"] . "-" . $row["sex"] ."
    "; } echo "
    "; foreach ($users as $row) { print $row["name"] . "-" . $row["sex"] ."
    "; }

    Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO

提交回复
热议问题