davy_yg's avatar
Level 27

Invalid argument supplied for foreach()

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\website_ids\IDS\recruitment.php on line 52

 <?php include("koneksi.php"); ?>

<?php $result = mysqli_query("SELECT * FROM tb_detail"); ?>

<?php foreach($result as $data){

            echo $data['position'];
        }

?>     

Any clue why the error appears?

Line 52: <?php foreach($result as $data){

0 likes
6 replies
manelgavalda's avatar

The problem is that $result is not returning an iterable so your foreach is not working.

jlrdw's avatar

Where is connection. And why do you always ask such basic questions here before taking a tutorial such as:

https://www.tutorialspoint.com/mysqli/

I know questions are fine, but most here learn stuff first, and ask a question if they get stuck. The idea is to at least have put forth an effort at some basics of the subject.

Something like

while($row = mysqli_fetch_assoc($result)) {
               echo "Name: " . $row["name"]. "<br>";
            }

Is right in the many free tutorials available World wide.

1 like
rawilk's avatar

Your error is you are trying to foreach around something that is not iterable. I don't really use mysqli_query at all, so I'm not sure what it returns, but obviously you can't iterate over it.

You should try to debug your script, it might help. I would start by dumping your $result variable to see what you actually have:

var_dump($result);

I searched on google, and you may need something like this:

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    print_r($row);
}

Example taken from: https://stackoverflow.com/questions/24470605/mysqli-query-foreach-works-differently-in-local-and-server

munazzil's avatar

You have to assign $result as a array.

     <?php include("koneksi.php"); ?>

     <?php $result=[]  ?>

      <?php $result = mysqli_query("SELECT * FROM tb_detail"); ?>   

      <?php foreach($result as $data){

          echo $data['position'];
     } 

     ?>
rawilk's avatar

@munazzil That doesn't do anything; you're overwriting $result on the next line.

Please or to participate in this conversation.