简体   繁体   中英

Php Foreach error Invalid argument

I got this error in my foreach in php:

Invalid argument supplied for foreach() in...

Code:

$database = new PDO('mysql:host=localhost;dbname=staff_tool', $user, '');
foreach ($database->query('SELECT id,firstname,lastname FROM `staff` SET categorie_bit = 0') as $testx) {
                var_dump($testx);
            }

Edited Code:

foreach ($database->query('SELECT id,firstname,lastname,categorie_bit FROM `staff` WHERE categorie_bit = 1 SET categorie_bit = 0') as $testx) {
            var_dump($testx);
        }

PHP s foreach expects param one to be an array of an iterable but it seems like you are passing in a statement object(printr) will output nothing more the select statement). You might wanna try:

      $stmt = $db->query($sql);
       $stmt->execute();
       $results  = $stmt->fetchAll();

         foreach($results as $result)
                var_dump($result);
$result = $database->query('SELECT id,firstname,lastname,categorie_bit FROM `staff` WHERE categorie_bit = 1 SET categorie_bit = 0');

// always check if you have a valid array ... you do not have any guarantees that SELECT query will return you a result set
if(is_array($result) && count($result) > 0) {
    foreach ($result as $testx) {
        var_dump($testx);
    }
}

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