php - foreach循环只运行一个

时间:2014-11-02 16:19:22

标签: php mysql for-loop pdo foreach

我有这个foreach循环:

$d=$dbh->prepare("SELECT * FROM users_rented WHERE since <= unix_timestamp(CURRENT_TIMESTAMP - INTERVAL 14 day) AND clicks_last <= unix_timestamp(CURRENT_TIMESTAMP - INTERVAL 14 day)");
    $d->execute();
        $array = array();
        foreach ($d as $data ) {
                 $array[] = $data['id'];
                     #print_r($new_array);
                     $userToRecycleFor = $data['user_by'];

                    $outcome =  $rentedrefs->_recycleMulti(0, $userToRecycleFor, $array, 1);


        }

当我在MySQL数据库中运行时,$d查询有2406个结果。

foreach循环仅在每次刷新页面时运行一次。因此,不是更新所有2406个用户(根据SQL查询),而是每次刷新只更新1个。

我做错了什么?

3 个答案:

答案 0 :(得分:1)

你需要在循环之前获取数据

$result = $d->fetchAll();

foreach ($result  as $data ) {
   $userToRecycleFor = $data['user_by'];
}

答案 1 :(得分:1)

你必须在循环之前获取结果。尝试更改这些行:

$d->execute();

$array = array();

$rows = $d->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $data) {
     $array[] = $data['id'];
     $userToRecycleFor = $data['user_by'];

     $outcome =  $rentedrefs->_recycleMulti(0, $userToRecycleFor, $array, 1);
}

答案 2 :(得分:0)

通常,您可以获取如下结果:(例如mysqli)

$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
$query = $mysqli->query("SELECT id, name, store FROM food");

while($array = $query->fetch_array(MYSQLI_ASSOC))
{
   $finalArray = $array;
}

foreach($finalArray as $item)
{
   // your process
}