简体   繁体   中英

php - foreach loop only runs one

I have this foreach loop:

$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);


        }

The $d query has 2406 results when I run it in the MySQL database.

The foreach loop is only being run 1 time on every page refresh. So instead of updating all 2406 users (as per the SQL query), it updates only 1 per refresh.

What am I doing wrong?

you need to fetch the data before looping

$result = $d->fetchAll();

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

You have to fetch the result before loop over it. Try to change these lines:

$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);
}

Normally, you fetch results like this: (eg 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM