As far as I am putting some efforts towards PHP and understanding why it is so hated by programmers all around, I have decided that the results from the queries should be always easily displayed in an HTML table. A beautiful one, if possible 🙂
Until now, what I have used to do was to tell php how to build the table, explicitly mentioning every column name. Today I have researched a little and I found out that this is really not needed – the PHP provides two beautiful options towards fetch_fields and fetch_arrays to understand the name of the columns in the table and the number of columns. Thus, without specifying them, with a few loops we are able to build table like this:
Just from the query. 🙂 And yes “Beauty” in programming is a formidable notion. 🙂
Ok, how have I done it? Pretty much through the help of two embedded loops, and the aforementioned fetch_fields and fetch_arrays.
Check the code yourself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<html> <head> <title>VitoshAcademy Table </title> <style> .nice_style{ background-color:yellow; color:blue; } .nicer_style{ background-color:silver; color:pink; } .header_style{ color:red; font-family:courier; font-size:160%; } </style> </head> </html> <?php function build_beautiful_table($my_result){ $counter = 0; $columns_number = $my_result->field_count; $titles = $my_result->fetch_fields(); echo "<table border='50'>"; echo "<tr class = header_style>"; foreach($titles as $title_needed){ echo "<th>" . htmlspecialchars($title_needed->orgname) . "</th>"; } echo "</tr>"; while($value = $my_result->fetch_array()){ if ($counter % 2 == 1){ $my_style = " class='nice_style' "; }else{ $my_style = " class='nicer_style' "; } $counter += 1; echo "<tr $my_style>"; for ($x = 0; $x< $columns_number; $x++){ echo "<td>" . htmlspecialchars($value[$x]) . "</td>"; } echo "</tr>"; } echo "</table>"; } $mysqli = new mysqli("localhost","root","","todo"); if($mysqli->connect_error){ echo "VitoshAcademy Error" . mysqli_connect_error(); exit(); } $my_result = $mysqli -> query("SELECT * FROM todos;"); build_beautiful_table($my_result); $my_result->close(); $mysqli->close(); ?> |
Enjoy your day and have fun 😀