简体   繁体   中英

Printing out MySQL tables in HTML

I am currently using the code below to print out a MySQL table. However, when I am printing multiple rows the format is pretty ugly. What is a way or command I could create columns similar to the Tab key to make it more aesthetically pleasing?

$google= mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($google)){
foreach($row as $cname => $cvalue){
    print "$cvalue\t <tr>";
}

print "<br>";
}

The query is printed using user input. using the

<form action="google.php" method="post">

command. I am also looking for a way to print this table on the same page as the HTML page that I accept the user input.

Your code is pretty good and only needs HTML added to it to make it look nicer. Using tables (this has not been tested but it should work):

$google = mysqli_query($query) or die(mysqli_error());

echo '<table>';

while($row = mysqli_fetch_assoc($google)) {
    echo '<tr>';
    foreach($row as $cvalue) {
        print '<td>'.$cvalue.'</td>';
    }
    echo '</tr>';
}

echo '</table>';

This is a quick and dirty way to output a MySQL table, but if you also want the names of the columns to show up, things get quite a bit trickier. Also, if your results contain special characters such as ">", this can mess up the output. If that happens, just look up the documentation for htmlspecialchars() .

If you want this table to show up on the same page as your form, just create a submit button and check the value in PHP like so:

if (isset($_POST['SubmitButtonNameHere'])  { ... }

I'm not sure of the structure of your form so this code might need to be different to determine whether the form has been submitted. You can put the code for creating the table inside of the curly braces and place the code for your form either above or below the if statement.

<tr> is an HTML element used to add rows to a <table> element. The <td> element adds cells to those rows. Also, your code was using mysql_* . This was changed to mysqli_* as the mysql prefix is deprecated in PHP. Hope this answers your question.

Just use this code instead :)

$google= mysql_query($query) or die(mysql_error());

echo "<table><tbody>";
while($row = mysql_fetch_assoc($google)){
foreach($row as $cname => $cvalue){
echo "<tr><td>".$cname."</td><td>".$cvalue."</td></tr>";
}
echo "</tbody></table>";

Done :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM