PDA

View Full Version : Display MySQL table within a table


Explosivo22
11-04-2009, 12:00 AM
I am still getting used to using mySQL and PHP. Have only been using for about a day and a half as of right now. I was just wondering if someone could help me take this code and make it so that the data I want it to display with be displayed inside of a table on my web page so it will have some sort of order to it and not just be in there. here is the code:

<?PHP
mysql_connect("localhost","username","password");
mysql_select_db("database");

$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($query))
{
$first = $row["first"];
$last = $row["last"];
$email = $row["email"];
echo $first." ".$last." ".$email."<br>";
}

?>


I just need that information to display in a table and i have no idea how much information there is so i will need it to expand as more information is added to the database.

Thanks in advance.

Kayla
11-04-2009, 04:55 AM
Give this a try, replace text in bold:

<?
$usr = "USER";
$pwd = "PASS";
$db = "DBNAME";
$host = "localhost";

# connect to database
$cid = mysql_connect($host,$usr,$pwd);
mysql_select_db($db);
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }

?>
<html>
<head>
<title>Results</title>
</head>
<body><center>
<?php

function drawtable($qr) {
// $qr = results of a mysql_query
$rows = mysql_num_rows($qr);
$toreturn = "<table style=\"float: center;\" border=\"2\">\n";
$toreturn .= "<tr>\n";
for ($i=0; $i<mysql_num_fields($qr); $i++) {
$toreturn .= "\t<th>".mysql_field_name($qr,$i)."</th>\n";
}
$toreturn .= "</tr>\n";
for ($i=0; $i<$rows; $i++) {
$row = mysql_fetch_row($qr);
$cols = sizeof($row);
$toreturn .= "<tr>\n";
for ($x=0; $x < $cols; $x++) {
if ($row[$x]==NULL){
$row[$x]='&nbsp;';
}
$toreturn .= "\t<td>$row[$x]</td>\n";
}
$toreturn .= "</tr>\n";
}
$toreturn .= '</table>';
return $toreturn;
}
$q = stripslashes($_POST['q']);
if (empty($q)) {
$q = 'select first, last, email from TABLE;';
}
mysql_select_db("DATABASENAME");
$result = mysql_query($q);

print "<b><font color=red>Your Query Result</font></b>\n";

echo drawtable($result);
echo '<table>
</table></center>
</body>
</html>';

Explosivo22
11-04-2009, 06:12 PM
Thanks. Works Just like I wanted it to. Thanks for all your help.