I am trying to learn PHP right now (I usually use Perl) and here's what I've found for looping through a DB and rendering the data: FROM http://webmonkey.wired.com/webmonkey/99/21/index3a.html <html> <body> <?php $db = mysql_connect("localhost", "root"); mysql_select_db("mydb",$db); $result = mysql_query("SELECT * FROM employees",$db); echo "<table border=1>\n"; echo "<tr><td>Name</td><td>Position</tr>\n"; while ($myrow = mysql_fetch_row($result)) { printf("<tr><td>%s %s</td><td>%s</td></tr>\n", $myrow[1], $myrow[2], $myrow[3]); } echo "</table>\n"; ?> </body> </html> PHP: The part I don't like is: printf("<tr><td>%s %s</td><td>%s</td></tr>\n",$myrow[1], $myrow[2], $myrow[3]); PHP: Is there a better way to access the data? "$myrow[1]" IMHO isn't a very good way to refer to data.
The $myrow is the name of the variable you provide so that can be changed to whatever you want. Also, so you don't have to refer to 1 2 and 3 for the fields in the result set you can use the function http://www.php.net/mysql_fetch_assoc and then you can refer to their names like $myrow['name'], $myrow['email']. You can also use the function http://www.php.net/mysql_fetch_array which will allow you to call it either way, $myrow[1] or $myrow['name']. <?php $db = mysql_connect("localhost", "root"); mysql_select_db("mydb",$db); $result = mysql_query("SELECT * FROM employees",$db); echo "<table border=1>\n"; echo "<tr><td>Name</td><td>Position</tr>\n"; while ($myrow = mysql_fetch_row($result)) { echo "<tr><td>{$myrow[1]} {$myrow[2]}</td><td>{$myrow[3]}</td></tr>\n"; // OR LIKE THIS //echo "<tr><td>".$myrow[1]." ".$myrow[2]."</td><td>".$myrow[3]."</td></tr>\n"; } echo "</table>\n"; ?> Code (markup):
Lazy way var_dump($myrow ); Lazy but visually attractive - rs2html in Adodb I understand PEAR has a datagrid as well
Thanks so much for the information, so instead of: while ($myrow = mysql_fetch_row($result)) { $myrow[1] } I can use: while ($myrow = mysql_fetch_assoc($result)) { $myrow['email'] } Is that correct?