RLJ Posted January 3, 2011 Share Posted January 3, 2011 I have the following code that searches my database and displays results in a table: $fields = array("field1", "field2", "field3") $cols = implode (', ', $fields); $result= mysql_query (" SELECT $cols FROM tablename WHERE ................... "); if (!$result) {die('Could not search database: ' . mysql_error());} if($result) { if(mysql_num_rows($result) == 0) { return "Sorry. No records found in the database"; } else { $table = "<table border='1' cellpadding='5' cellspacing='5'>"; while($arr = mysql_fetch_array($result, MYSQL_ASSOC)) { $table .= "\t\t<tr>\n"; foreach ($arr as $val_col) { $table .= "\t\t\t".'<td>'.$val_col.'</td>'."\n"; } $table .= "\t\t</tr>\n"; } $table .= "</table>"; echo $table; } mysql_free_result($result); } As you can see each of the MySQL table fields specified by $fields is displayed in a new column in the html table. I want to change this so that e.g. "field3" is displayed in a new row instead. So, instead of the html table looking like: | "field1-result1" | "field2-result1" | "field3-result1" | | "field1-result2" | "field2-result2" | "field3-result2" | | "field1-result3" | "field2-result3" | "field3-result3" | I want it to look like: | "field1-result1" | "field2-result1" | | "field3-result1" | | | "field1-result2" | "field2-result2" | | "field3-result2" | | | "field1-result3" | "field2-result3" | | "field3-result3" | | I guess this is quite straightforward, but I can't work it out! Pls help! Thanks. Link to comment https://forums.phpfreaks.com/topic/223224-display-mysql-query-results-in-html-table/ Share on other sites More sharing options...
jcbones Posted January 3, 2011 Share Posted January 3, 2011 Change your while statement to: while($arr = mysql_fetch_array($result, MYSQL_NUM)) { $table .= "\t\t<tr>\n"; $table .= "\t\t\t".'<td>'.$arr[0].'</td>'."\n \t\t\t".'<td>'.$arr[1].'</td> </tr> <tr>'. "\n\t\t\t".'<td colspan="2">'.$arr[2].'</td>'."\n"; $table .= "\t\t</tr>\n"; } Link to comment https://forums.phpfreaks.com/topic/223224-display-mysql-query-results-in-html-table/#findComment-1154036 Share on other sites More sharing options...
RLJ Posted January 3, 2011 Author Share Posted January 3, 2011 Thanks! Link to comment https://forums.phpfreaks.com/topic/223224-display-mysql-query-results-in-html-table/#findComment-1154340 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.