Create HTML table from sql table - php

I have a table in a SQL database with the following fields: ID, Name, Email, University, Languages, and Experience. I want to create an html table that fetches data from SQL and outputs the last 10 results? How would I do that?
I'm sorry if this is a very simple question, I have very little knowledge in PHP and SQL.
Here's the code I have right now that just displays the name and not in a table:
<html>
<head>
<title>Last 5 Results</title>
</head>
<body>
<?php
$connect = mysql_connect("localhost","root", "root");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("apploymentdevs");
$results = mysql_query("SELECT * FROM demo");
while($row = mysql_fetch_array($results)) {
echo $row['Name'] . "</br>";
?>
</body>
</html>

Here is something that should help you to create the table and get more knowledge of php and mysql.
Also you should move your connection logic and query to the beginning of your process, thus avoiding errors while loading the page and showing a more accurate error than just the mysql_error.
Edit: If your ids are incrementing, then you could add the ORDER BY clause,
change: SELECT * FROM demo LIMIT 10
to: SELECT * FROM demo LIMIT 10 ORDER BY id
<html>
<head>
<title>Last 10 Results</title>
</head>
<body>
<table>
<thead>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
$connect = mysql_connect("localhost","root", "root");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("apploymentdevs");
$results = mysql_query("SELECT * FROM demo LIMIT 10");
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td><?php echo $row['Id']?></td>
<td><?php echo $row['Name']?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>

I got very annoyed pasting together the same code over and over again to build HTML tables from SQL queries.
So, here we go with a function that takes mysqli results and pastes them together to an plain simple HTML table that has column names according to those in the database:
function sql_to_html_table($sqlresult, $delim="\n") {
// starting table
$htmltable = "<table>" . $delim ;
$counter = 0 ;
// putting in lines
while( $row = $sqlresult->fetch_assoc() ){
if ( $counter===0 ) {
// table header
$htmltable .= "<tr>" . $delim;
foreach ($row as $key => $value ) {
$htmltable .= "<th>" . $key . "</th>" . $delim ;
}
$htmltable .= "</tr>" . $delim ;
$counter = 22;
}
// table body
$htmltable .= "<tr>" . $delim ;
foreach ($row as $key => $value ) {
$htmltable .= "<td>" . $value . "</td>" . $delim ;
}
$htmltable .= "</tr>" . $delim ;
}
// closing table
$htmltable .= "</table>" . $delim ;
// return
return( $htmltable ) ;
}
Example Usage:
$DB = new mysqli("host", "username", "password", "database");
$sqlresult = $DB->query( "SELECT * FROM testtable LIMIT 1 ;" ) ;
echo sql_to_html_table( $sqlresult, $delim="\n" ) ;

Calling table( $result ); on your query results will generate a html based table regardless of the size of the sql array you feed it. I hope this helps :)
<?php
function table( $result ) {
$result->fetch_array( MYSQLI_ASSOC );
echo '<table>';
tableHead( $result );
tableBody( $result );
echo '</table>';
}
function tableHead( $result ) {
echo '<thead>';
foreach ( $result as $x ) {
echo '<tr>';
foreach ( $x as $k => $y ) {
echo '<th>' . ucfirst( $k ) . '</th>';
}
echo '</tr>';
break;
}
echo '</thead>';
}
function tableBody( $result ) {
echo '<tbody>';
foreach ( $result as $x ) {
echo '<tr>';
foreach ( $x as $y ) {
echo '<td>' . $y . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
}

You might be interested in fetching with mysql_fetch_assoc() (so that you get the data in an associative array : keys=>value). In the keys are your column names ; so, for each line, you can loop through each column (with array_keys()) and print its value.
$results = mysql_query("SELECT * FROM demo");
while($row = mysql_fetch_assoc($results)) {
foreach (array_keys($row) as $column) {
echo $row[$key] . "</br>";
}
}
(After that, you can cache array_keys($row) in a variable which is only set once, because its value won't change while you run through the results.)

Even though it's been a while I'm going to put my 2 cents in: use functions (even better - classes). Creating tables from mysql results is a very common task.
<!DOCTYPE html>
<html>
<head><title>Create Tables from MySQL using functions</title></head>
<body>
<?php
db_connect();
// assuming you have an auto increment id as the first column
$result = mysql_query("SELECT * FROM demo ORDER BY 1 DESC LIMIT 10");
print createTable(array_result($result));
?>
</body>
</html>
<?php
/**
* Quick mysql result function
*
* #param $result
* #return array
*/
function array_result($result)
{
$args = array();
while ($row = mysql_fetch_assoc($result)) {
$args[] = $row;
}
return $args;
}
/**
* Connect to db
*
* #param string $db_host
* #param string $db
*/
function db_connect($db_host = "localhost", $db = "apploymentdevs")
{
$connect = mysql_connect($db_host,"root", "root");
if (!$connect) {
die(mysql_error());
}
mysql_select_db($db);
}
/**
* Create a table from a result set
*
* #param array $results
* #return string
*/
function createTable(array $results = array())
{
if (empty($results)) {
return '<table><tr><td>Empty Result Set</td></tr></table>';
}
// dynamically create the header information from the keys
// of the result array from mysql
$table = '<table>';
$keys = array_keys(reset($results));
$table.='<thead><tr>';
foreach ($keys as $key) {
$table.='<th>'.$key.'</th>';
}
$table.='</tr></thead>';
// populate the main table body
$table.='<tbody>';
foreach ($results as $result) {
$table.='<tr>';
foreach ($result as $val) {
$table.='<td>'.$val.'</td>';
}
$table.='</tr>';
}
$table.='</tbody></table>';
return $table;
}

I hope you know how to make a table in HTML, with <table>, <tr> and <td>.
Fix a table with that in your while-loop and use "SELECT * FROM demo LIMIT 10" as SQL-query.

Related

how to output mysql table data into an html table without knowing what $row is like phpmyadmin

Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,

SQL loop won't print column names

I have several columns in my database and I would like to print out all the column names, i.e. the names of the people in the database.
I'm having trouble with selecting ONLY the column names, this piece of code will run the loop but only the $i will print, not the actual names of the columns. Any advice? Thanks
$query = mysql_query("SELECT * FROM People");
$i = 1;
while($row = mysql_fetch_assoc($query)) {
$name = $row['query'];
if ($count > '1') {
?>
<table>
<tr>
<td><p><b><?php print( $name . "</p></td></tr>");
$i = $i + 1;
?>
P.s.
I tried with:
select COLUMN_NAME from Names.COLUMNS where TABLE_NAME = 'Names' but this won't work either, it tells me: access denied, don't really know why
Here is the code to get column names for your table.
$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']."<br>";
}
But, as you get access denied. It means you do not have privilege to access table metadata.
So you can use either,
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
// Here $columns is array and it contains all column name
}
}
I think you should try this:
$query = "SELECT * FROM People";
$result = mysqli_query( $conn, $query );?>
<table>
<?php
while($row = mysqlsi_fetch_assoc( $result ) ){
?>
<tr>
<td><p><?php print( $row->id );?></p></td>
<td><p><?php print( $row->name );?></p></td>
<td><p><?php print( $row->lastname );?></p></td>
</tr>
<?php
} ?>
</table>
Assuming,your SQL table has these fields: id, name, lastname.
Inside your while loop you could use
foreach($row as $column => $value){
printf("Column: %s has value: %s\n", $column, $value);
}
As mysql_fetch_assoc returns an associative array so you want the key => value information.
HTH
Use mysql_field_name function in php to get column name
$query = mysql_query("SELECT * FROM People");
$i = 1; $j=0; // I have declared $j incrementor
while($row = mysql_fetch_assoc($query)) {
$name = $row['query'];
$columnname = mysql_field_name($query, $j); // This gives the column name of table.
if ($count > '1') {
?>
<table>
<tr>
<td><?php echo $columnname; ?></td>
<td><p><b><?php print( $name . "</p></td></tr>");
$i = $i + 1;
$j = $j + 1;
?>

Display SQLITE output in column rather than row

At the moment I have the below script which auto generates the table names and row data automatically by looking at a sqlite table. So regardless of if you have 2 or 10 columns this script works.
At the moment the script outputs the results like this:
Output currently appears as a Row
I have tried altering the script so that it outputs the results like below. Can someone assist or guide me in the right direction to achieve this?
Is it possible to output the results of the query in the below format: going down in a column rather than across as a row ?
Output should appear as a Column
<?
$ED = $_GET['ED'];
$ID = $_GET['ID'];
$table_name = $_GET['table'];
?>
<table border="1">
<tr>
<td>
<table>
<?php // Display all sqlite column names for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
if ($table['name'] == "ID") {
echo "<tr><td>" . $table['name'] . "</td></tr>";
} else {
$table_name_header = ucwords(strtolower(str_replace('_', ' ', $table['name'])));
echo "<tr><td>" . $table_name_header . "</td></tr>";
}
}
?>
</table>
</td>
<td>
<table>
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
</table>
</td>
</tr>
</table>
Modifying the code to the below by putting the data into an combined array and then pulling it back via a loop it will display as required:
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
$column_data[] = $row[$col];
// echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
<?
$array = $columns;
$array2 = $column_data;
$result = array_combine($array, $array2);
//print_r($result);
?><br><br>
<center>
<table border="0" cellpadding="2" cellspacing="2" color="#4B708D">
<thead>
<?
foreach($result as $key => $value) {
echo "<tr><td bgcolor='#c6d5e1'>$key</td><td bgcolor='#FFFFFF'>$value</td></tr>";
}
?>
</thead>
</table>

Displaying all tables in a database

How do I display out all the information in a database (All tables and records) using PHP? I read displaying tables as HTML table but how do I do it for all the tables?
I tried the example here:
http://davidwalsh.name/html-mysql-php
But it shows the table names, how do I also display all the values?
Okay got it .. try this
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "username", "password", "DB");
$result = $mysqli->query("SHOW TABLES");
while ($row = $result->fetch_row()) {
$table = $row[0];
echo '<h3>', $table, '</h3>';
$result1 = $mysqli->query("SELECT * FROM `$table`");
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
$column = $mysqli->query("SHOW COLUMNS FROM `$table`");
echo '<tr>';
while ($row3 = $column->fetch_row()) {
echo '<th>' . $row3[0] . '</th>';
}
echo '</tr>';
while ($row2 = $result1->fetch_row()) {
echo '<tr>';
foreach ($row2 as $key => $value) {
echo '<td>', $value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
$mysqli->close();
you can use the recursive function to display the tree Structure of your database.
Here is the a sample code from http://webcodingeasy.com/PHP/Simple-recursive-function-to-print-out-database-tree-structure
<?php
function print_menu($id = 0)
{
// get all records from database whose parent is $id
$result = $query->select_result("*", "table", "where parent = '".$id."'");
//check if there are any results
if($result != 0)
{
echo "<ul> n";
while($row = $query->fetch($result))
{
//print result and call function to check if it has children
echo "<li>".$row['name']."</li> n";
print_menu($row['ID']);
}
echo "</ul> n";
}
}
print_menu();
?>
If you want to pull all tables with the values in mysql, you can use the following code:
<?php
mysql_connect ("localhost", "DB_USER", "DB_PASSWORD"); //your mysql connection
mysql_select_db('DB_NAME') or die( "Unable to select database"); //your db name
$tables = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema='DB_NAME'"); //pull tables from theh databsase
while ($table= mysql_fetch_row($tables)) {
$rsFields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($field = mysql_fetch_assoc($rsFields)) {
echo $table[0].".".$field["Field"].", "; //prints out all columns
}
echo $table[0];
$query = "SELECT * FROM ".$table[0]; //prints out tables name
$result = mysql_query($query);
PullValues($result); //call function to get all values
}
//function to pull all values from tables
function PullValues($result)
{
if($result == 0)
{
echo "<b>Error ".mysql_errno().": ".mysql_error()."</b>";
}
elseif (#mysql_num_rows($result) == 0)
{
echo("<b>Query completed. No results returned.</b><br>");
}
else
{
echo "<table border='1'>
<thead>
<tr><th>[Num]</th>";
for($i = 0;$i < mysql_num_fields($result);$i++)
{
echo "<th>" . $i . " - " . mysql_field_name($result, $i) . "</th>";
}
echo " </tr>
</thead>
<tbody>";
for ($i = 0; $i < mysql_num_rows($result); $i++)
{
echo "<tr><td>[$i]</td>";
$row = mysql_fetch_row($result);
for($j = 0;$j < mysql_num_fields($result);$j++)
{
echo("<td>" . $row[$j] . "</td>");
}
echo "</tr>";
}
echo "</tbody>
</table>";
} //end else
}
?>
I am using this and works fine in mysql, for mysqli you need to tweak it a very little.

How to echo out table rows from the db (php)

i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])

Categories