php - Why is my foreach loop not working as expected? -


I am quite new to PHP development, but I think I'm picking it up at speed, but when I took XAMPP into a real host, then I hit a bit of a problem. I am trying to do something like that.

  $ cast_list = mysqli_query ($ dblink, $ sql); Foreign currency ($ cast_list $ as role) {resonant "<<">  $ Role ['December_'] "& Lt; / td>"; }  

It works on XAMPP which is installed on my home PC, but this does not work on the hosting system I do test with. The actual query is working perfectly, so there is no problem. I can see the correct results on XAMPP in PHPMyAdmin and when I change the code as follows

$ cast_list = mysqli_query ($ dblink, $ sql); $ Y = mysqli_num_rows ($ cast_list); {$ Role = mysqli_fetch_assoc ($ cast_list) for ($ X = 0; $ x & lt; $ y; $ x ++); Echo "& lt; tr & gt; & lt; td width = '50%' & gt;". $ Role ['Dec_as] "& Lt; / td>"; }

The second code block will produce the desired effect. The first code block will apparently kill again 5 times, but there will be no meaningful data. In fact, a var_dump ($ role) for the first code block shows that it is NULL .

If needed, but maybe a logical reason why foreach is not working properly for me?

mysqli_query () You can use an array with foreach or Return the array object (not) The return type mysqli_query () is a resource that will bring you the loop in the same way as the second loop.

It is easy to use () instead of ():

  $ cast_list = mysqli_query ($ dblink, $ Sql); While ($ role = mysqli_fetch_assoc ($ cast_list)) {resonant "<<"> "; }  

When looping is received at the end of the result set, the loop will close automatically. You do not need to know the number of rows before the loop.


Repeat your comment:

After this, I have to admit that my answer is not entirely up to the truth. Or is not true for some versions of PHP.

In PHP 5.4, a mysqli_result resource added Iterator functionality, you can actually use it foreach () . But your host apparently uses the old version of PHP.

The best practice is to develop on the same version of the all software that you will deploy, so you have not been caught by such surprises.


Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -