PHP MySQL data FOR loop

for-loopMySQLPHP

<?php

//function to create a table
function makeTable($table, $columns){
    $numFields = count($columns)-1;

    $query = 'SELECT * FROM '.$table;
    $result = mysql_query($query);
    $arrayResult = mysql_fetch_array($result);
    $num_rows = mysql_num_rows($result);

    for ($x = 1; $x <= $num_rows; $x++){ //1st for loop
        echo '<tr>';
            for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
                echo '<td>'.$arrayResult[$columns[$i]].'</td>';
            }
        echo '</tr>';
    }
}

?>

$columns is an array entered by the user eg: $columns = array ('Column1', 'Column2', 'Column3);. These are the names of the columns which are in a given $table.

My idea was to create a function that displays the data from the MySQL table with the info from the $columns array. The problem is in the second for loop. The value of $i is reset every time the first loop is done, so I get the same result over and over again (the number of rows in the table).
My question is this: How do I keep the $i in the second loop from resetting?

Thank you in advance.

Best Answer

The reason you get the same result over and over is not because $i, but $arrayResult.

The right way is like this:

//function to create a table
function makeTable($table, $columns){
    $numFields = count($columns)-1;
    $query = 'SELECT * FROM '.$table;
    $result = mysql_query($query);

    while ($arrayResult = mysql_fetch_array($result)){
        echo '<tr>';
            for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
                echo '<td>'.$arrayResult[$columns[$i]].'</td>';
            }
        echo '</tr>';
    }
}