spencdev spencdev - 3 months ago 8
PHP Question

While foreach loop returns random list of numbers

I have several columns I am wanting to turn into a table with the value as the row it pertains to. EXAMPLE:

In my table I have 4 columns named

column1 column2 column3 column4
. Those columns only have 1 row that will be found. Such as
SELECT column1, column2, column3, column4 FROM operations WHERE active = '1'



The row it finds looks something like this (with columns)

column1 | column2 | column3 | column4
_____________________________________
3456 | 265 | 795 | 425


I want it to display a table that looks like:

column1 | 3456
column2 | 265
column3 | 795
column4 | 425


The following script works, but it also displays a random list of numbers I believe that are associated with the columns somehow.

function oreAmount() {
$sql = mysqli_query($this->con, "SELECT `column1`,`column2`,`column3`,`column4` FROM operations WHERE active = '1'");
while ($row = mysqli_fetch_array($sql)) {
$rows[] = $row;
foreach ($row as $key => $var) {
echo "<tr><td>$key</td><td>$var</td></tr>";
}
}
}


This function displays the following:

0 | 3456
column1 | 3456
1 | 265
column2 | 265
2 | 795
column3 | 795
3 | 425
column4 | 425


I'm not sure why or where the numbers are coming from and I need them removed.

Answer

You should use mysqli_fetch_assoc instead of mysqli_fetch_array.

Explanation

mysqli_fetch_array is always return result with two kind of indexing.

  1. MYSQLI_NUM (indexing in numeric keys)
  2. MYSQLI_ASSOC (indexing in associate names)

So either pass param which kind of indexing you want to retrieve your results like

mysqli_fetch_array($result,MYSQLI_ASSOC).

or simple use

mysqli_fetch_assoc