Creating array of fields then looping through set in PHP

290
June 29, 2017, at 05:18 AM

I'd like to simplify how my app builds a query and loops through the results. Most of the actual code works, except that PHP does not display all of the results fetched from my query.

PREFACE: example code ahead, do not use in production.

First I build the query.

$arr_fields = array('color', 'number', 'size');
$select_fields = implode(', ', $arr_fields);
$q = "SELECT $select_fields FROM supplychain";

Now I execute the query then loop through the result set.
Pro tip: don't use this code for anything important - it's for demo purposes only.

echo "<table>";
    $res = doQuery($q);
    // create report body
    foreach($res as $r)
    {
         // set values from array of field names
         $row_fields = '';
         foreach ($arr_fields as $f)
         {
            // set current $arr_field value inside a table cell...
            $row_fields.= "<td>$r[$f]</td>";
         }
         // display the row
         echo "<tr>$row_fields</tr>";
    }
echo "</table>";

The first database value from $arr_fields (color) is output as expected, the rest are not.

The assembled query issued at a MySQL console shows values for color, number and size. There aren't any SQL errors generated by the script.

Why is PHP displaying the first field's value but skipping the other two?

Answer 1

Change this line:

$row_fields.= "<td>$r[$f]</td>";

to:

$row_fields.= "<td>".$r[$f]."</td>";
Answer 2

The issue turned out to be a space before each of the fieldnames in my array (not shown in the example above).

The field array actually was

$arr_fields = array('color', ' number', ' size');

Once I removed the spaces, values showed up as usual. Thanks for Norbert for helping point me in the right direction via additional testing.

Rent Charter Buses Company
READ ALSO
MySQL LOAD XML LOCAL slows down after first 100k entries

MySQL LOAD XML LOCAL slows down after first 100k entries

I am trying to import a large XML (arround 700MB) into a MySQL databaseIt is working so far but the thing is, it is terribly slow

335
Why do I not get a response from JSON post request unless the number of rows is limited?

Why do I not get a response from JSON post request unless the number of rows is limited?

I am using a JSON post request to return rows from a mySQL databaseMy server-side language is php and unless I limit the results in sql to about 45 I don't get a response

239
How to convert mySQL time to python time?

How to convert mySQL time to python time?

I'm trying to retrieve time variable from mySQL database using pythonBelow shows the python code I use to retrieve the time variable from mySQL database

384
Laravel query Builder with DATE mysql function

Laravel query Builder with DATE mysql function

Hi I have a query in my laravel project which should retrieve dates between rangesMy query is:

452