I am new to both PHP and MYSQL and I am trying to figure out how can I display the result of my query nicely in a table. I am new to both PHP and MYSQL as well as HTML.
So far I managed to create a database on my machine, created some tables, inserted some data into a table and created a PHP page that I can use to issue a query. I managed to retrieve the desired query but I have no idea how to make it look nice, in a table and also display the column names. Also I am not sure how to handle random table info as well, since my code is hardcoded for a specific table. Here is my PHP code so far.
<html>
<head><title>PHP MYSQL</title></head>
<body>
<form action="." method="GET">
<textarea name="query" cols="60" rows="8"></textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
DEFINE('DB_USER', 'cs143');
DEFINE('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'TEST');
$db_connection = mysql_connect("localhost", "cs143", "")
OR die("could not connect to databaseaaa !!!");
mysql_select_db("TEST", $db_connection);
$query = $_GET[query];
$rs = mysql_query($query, $db_connection);
if(!$rs)
{
die("Query failed");
}
while($row = mysql_fetch_row($rs))
{
$name = $row[0];
$age = $row[1];
print "$name, $age<br />";
}
?>
</body>
</html>
<table>
<th>
<td>Name</td>
<td>Age</td>
</th>
<?php while($row = mysql_fetch_row($rs)) { ?>
<tr>
<td><?php echo $row[0]; ?></td>
<td><?php echo $row[1]; ?></td>
</tr>
<?php } ?>
</table>
I think I found what I was looking for. I use the following code, which fetches the number of columns and their names and displays data correctly.
<h2>Query result:</h2>
<html><body><table border=1 cellspacing=1 cellpadding=2><tr align="center">
<?php
//print out first row of header fields
$i = 0;
while($i < mysql_num_fields($rs))
{
//meta holds column information (name, description, etc.)
$meta = mysql_fetch_field($rs, $i);
//output column names along with bold HTML tags via echo
echo '<td><b>' . $meta->name . '</b></td>';
$i = $i + 1;
}
?>
<?php
//print out the actual query results
$i = 0;
while($row = mysql_fetch_row($rs))
{
echo '<tr align="center">';
$count = count($row);
$y = 0;
while($y < $count)
{
$c_row = current($row);
//if any value is NULL (blank), replace it with N/A
if($c_row==NULL)
echo '<td>N/A</td>';
else
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '</tr>';
$i = $i + 1;
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.