0

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?

2

3 Answers 3

1

you need to fetch the data before looping

$result = $d->fetchAll();

foreach ($result  as $data ) {
   $userToRecycleFor = $data['user_by'];
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.