I'm performing a request on a database which returns an array. I'm using a foreach loop to go through the values.
Database (only 1 entry)
id | field1 | field2 | field3 | field4 | field5
---|--------|--------|--------|--------|--------
1 | value1 | | value3 | value4 | value5
PHP Source code
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$q = mysqli_query($mysqli, "SELECT * FROM my_table");
echo "<ul>";
while($q = mysqli_fetch_array($q))
{
foreach ($q as $key => $value)
{
if($value != NULL)
{
echo "<li>".$value . "</li>";
// Line below used to show column name and corresponding value
//echo "<li><strong>{$key}</strong> / <em>{$value}</em></li>";
}
}
}
echo "</ul>";
Expected HTML output
<ul>
<li>value1</li>
<li>value3</li>
<li>value4</li>
<li>value5</li>
</ul>
Current output
<ul>
<li>1</li>
<li>1</li>
<li>value1</li>
<li>value1</li>
<li>value3</li>
<li>value3</li>
<li>value4</li>
<li>value4</li>
<li>value5</li>
<li>value5</li>
</ul>
Current issue
As you can see, I current have everything in double, and for some wierd reason, I'm getting the row ID, or so I assume considering I do not get a second row when I add a new row to the database.
Alternate code
Using the commented line, I get this output:
<ul>
<li>0 / 1</li>
<li>id / 1</li>
<li>1 / value1</li>
<li>field1 / value1</li>
<li>3 / value3</li>
<li>field3 / value3</li>
<li>4 / value4</li>
<li>field4 / value4</li>
<li>5 / value5</li>
<li>field5 / value5</li>
</ul>
From what I understand
- A
whileloop would allow me to go through each row from the database. - A
foreachloop is similar to awhileloop, but instead of going through database entries, it goes through the key/value pairs from anarray.
(Please feel free to correct me if I am wrong about these previous statements.)
Thinking outloud
- I'm starting to wonder, as I write this question, if the
whileandforeachseem kind of redundant in that both seem would parse the values, probably causing my duplicates...? - Wouldn't the row number (in this case
1) be a key?
while($r = mysqli_fetch_array($q))?