Printing a query in html table

Hi,
I’m just wondering if anyone would be able to help me with a problem I’ve been having. I’m trying to print data from a mysql query into an html table. I’m using a nested for loop and I’m very nearly there. I just can’t seem to work out how to print more than one line of results. The code I have at the minute is:

$query = "select TeacherName, Age, Subject from Teacher WHERE schoolcode =" . $schoolcode; // Specifying the query and using the variable school code from the frontend HTML form to make it reusable

$result = mysqli_query($con, $query) or die("Invalid query"); //Running the query and storing it in result
$numrows = mysqli_num_rows($result);  // gets number of rows in result table
$numcols = mysqli_num_fields($result);   // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$row = mysqli_fetch_array($result);

print "<table border=1><tr>";
for($x=0;$x<$numcols;$x++){
print "<th>" . $field[$x]->name . "</th>";
}
print "</tr>";

for($j=0; $j<$numrows; $j++) {   // for loop goes round until there are no rows left
 print "<tr>";
	 for ($k=0; $k<$numcols; $k++) {    //  goes around until there are no columns left
        print "<td>" . $row[$k] . "</td>"; //Prints the data
  }
   print "</tr>";
}

print "</table>";

mysqli_close($con); 
 ?> 

The code very nearly works and does print out the html table with correct results. The problem is that it prints out one row of results, then repeats this same row of results on the next row, rather than printing the next row of results which I want. Can anyone help me with this problem?

Many Thanks

It’s because you’re never going to the next row in the loop…change this

for($j=0; $j&lt;$numrows; $j++) {   // for loop goes round until there are no rows left

to this

while ($row in mysqli_fetch_array($result)) {

Great. Thank you!

Sorry I actually just tried this and for some reason it brings up the error Parse error: syntax error, unexpected ‘in’ (T_STRING) in… Do you know why this is?

Thanks

Sorry should be $row = not $row in

Thanks Dave. I tried that too and for some reason it omits the first row of results and skips onto the second. Do you know why this is?

Remove this line right below where $field gets the values assigned to it.

Works perfectly now. Thank you for your help. Much appreciated.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.