How to create a dynamic table in PHP from SQL - php

I try to make a dynamic table. The data comes from a database.
It works so far, but I want to make a table with seperate fields, not like my way.
My code so far:
<?php
$result = mysql_query("SELECT buyTime, untilTime FROM users WHERE userName='".$_SESSION["user"]."';");
$num_rows = mysql_num_rows($result);
echo("Buy Date"."|Expire Date");
echo "<br />";
echo "<br />";
while ($row = mysql_fetch_array($result)) {
echo '<th>'.$row['buyTime'].'</th>'."|".'<th>'.$row['untilTime'].'</th>';
echo "<br />";
}
?>
The result:
Click here
So how can I make a correct table, not a pseudo one?
Thank you :)
Regards

Use a table element on html and put your php loop code inside the tbody element. How to properly create a table;
<table>
<thead>
<tr>
<th>Buy Date</th>
<th>Expire Date</th>
</tr>
</thead>
<tbody>
<?php
$result = mysql_query("SELECT buyTime, untilTime FROM users WHERE userName='".$_SESSION["user"]."';");
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>'.$row['buyTime'].'</td><td>'.$row['untilTime'].'</td>';
echo '</tr>'
}
?>
</tbody>
</table>

<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h2>Colored Table Header</h2>
<table>
<tr>
<th>Buy Date</th>
<th>Expire Date</th>
</tr>
<?php
$result = mysql_query("SELECT buyTime, untilTime FROM users WHERE userName='".$_SESSION["user"]."';");
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['buyTime']; ?></td>
<td><?php echo $row['untilTime']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
NOTE: An HTML table is defined with the <table>tag.
Each table row is defined with the <tr> tag. A table header is defined with the <th> tag. By default, table headings are bold and centered. A table data/cell is defined with the <td> tag. Moreover Mysql is outmoded please try learn new approach. You can learn it on w3schools php
Good Luck!!!

Related

How can I edit the rows of data in a table using data from a database?

How can I format and style the rows of data in this table where it's displaying my data?
<table class="table">
<tr bgcolor=" #b366ff">
<th>Game</th>
<th>Date</th>
<th>Score</th>
<th>Venue</th>
</tr>
<?php
$sql = "SELECT * FROM game WHERE username = '{$users}' AND savename = '{$saves}';";
$result = mysqli_query($connection, $sql);
?>
<?php
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['team']."</td>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['score']."</td>";
echo "<td>".$row['venue']."</td>";
echo "</tr>";
}
?>
using a CSS class?
<style>
.tr1{background-color:#333;}
.td1{background-color:#999;}
</style>
echo "<tr class="tr1">";
echo "<td class="td1">".$row['team']."</td>";
You can do same as you do in normal HTML, you can use
.table tr{
background-color: grey;
}
Also you can use nth child selecter to style the elements.

How to show the message in php if there is no data in table [duplicate]

This question already has answers here:
Checking if mysqli_query returned any values?
(2 answers)
Closed 1 year ago.
I have a report, which has a few prompts, and based on the prompt selection, sometimes there might be no records in the report. In such cases, I want to show a message NO RECORDS FOUND on the Cover Page.
Can anyone tell me how I do this?
<?php
error_reporting(0);
include("connection.php");
session_start();
if(!($_SESSION['email']))
{
echo "please login first to access this page";
header("refresh:3;url=index.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
body
{
margin: 0;
padding: 0;
}
table
{
border-collapse: collapse;
width: 100%;
font-family: sans-serif;
font-size: 15px;
}
th,td
{
padding: 5px;
text-align: left;
}
tr:nth-child(even)
{
background: #edf0f5;
}
th
{
background: #00A800;
color: white;
padding: 5px;
font-family: sans-serif;
}
a
{
text-decoration: none;
color: #00A800;
}
a:hover
{
text-decoration: underline;
}
</style>
<title>View all the data</title>
</head>
<body>
<table>
<tr>
<th>Roll NO</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Class</th>
<th>Class Section</th>
<th>Phone number</th>
<th>Email Address</th>
<th>Address</th>
<th>Edit</th>
<th>View Fees</th>
<th>Attendance</th>
</tr>
<?php
$select="select *from student where class='1' AND section='B' ";
$run=mysqli_query($con,$select);
$i=0;
while($row=mysqli_fetch_array($run))
{
$id=$row['id'];
$s_name=$row['s_name'];
$f_name=$row['f_name'];
$class=$row['class'];
$section=$row['section'];
$phone=$row['phone'];
$email=$row['email'];
$address=$row['address'];
$i++;
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $s_name;?></td>
<td><?php echo $f_name;?></td>
<td><?php echo $class;?></td>
<td><?php echo $section;?></td>
<td><?php echo $phone;?></td>
<td><?php echo $email;?></td>
<td><?php echo $address;?></td>
<td>Edit</td>
<td>Fees</td>
<td>Attendance</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
You can use mysqli_num_rows() to check the number of rows in a result
$select = "select *from student where class='1' AND section='B' ";
$run = mysqli_query($con, $select);
if (mysqli_num_rows($run > 0)) {// check if your query return result
// your code
} else {
echo "NO result found";
}
Read http://php.net/manual/en/mysqli-result.num-rows.php
You need to check if rows are returned, if not, show error.
$i = 0;
while($row=mysqli_fetch_array($run)) {
// Your code
$i++;
}
if ($i <1) {
?>
<tr><td colspan="11">There are no records.</td></tr>
<?php
}
Explanation:
1) We have taken a variable $i, initialized to 0
2) In while loop, it is incremented.
3) If we have records, after while loop, we will get $i more than 0.
4) If it is still 0 that is less than 1, it means there are no records and show the error message.
You can use mysqli_num_rows to count the number of rows returned:
Returns the number of rows in the result set.
Since, mysqli_num_rows will return 0 if there's no result, you can use ! to check if the result is false.
$select="select *from student where class='1' AND section='B' ";
$run=mysqli_query($con, $select);
if (!mysqli_num_rows($run)) {
echo "No result is found";
} else {
// to do if there's result
}

PHP echo tables

Overview
I have some data stored in MySql database related to Products. I am trying to retrieve this data and display it on a page using HTML table.
The PHP and MySql has gone well and all the data is retrieved but it is displayed in a very messy manner.
Here is what I have as a layout:
What I am aiming to achieve is to further divide the results table add more columns rows to make the data more readable
Something like this;
The code: PHP, MySQL & HTML:
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
$sql = mysql_query("SELECT * FROM products");
echo "<table id='display'>";
while($rows = mysql_fetch_array($sql))
{
echo"<br>";
echo"<tr><td>";
echo"$rows[$product_name]<br></td>";
echo"<td><img src=$rows[$product_image] height='200px' width='200px'><br></td>";
echo"<td>Avalible: $rows[$product_qua]<br></td>";
echo"<td>Price: $rows[$product_price]<br></td>";
echo"<td>Description: $rows[$product_des]<br></td>";
echo"</tr>";
}
echo "</table>";
?>
CSS responsible for this part:
#display{
float:left;
border: 5px solid black;
margin-left:100px;
}
just add some padding or a border to the table cells:
table#display td{
border: 1px solid black;
padding:0 8px;
}
Edit: What you could do as well:
<table id='display'>
<?php while($rows = mysql_fetch_array($sql)): ?>
<!-- <br> <- why a break? it's not in the correct spot anyway -->
<tr><td>
<?php echo $rows[$product_name]; ?><br>
</td>
<td> - </td>
<td><img src="<?php echo $rows[$product_image]; ?>" height='200px' width='200px'><br></td>
<td> - </td>
<td>Avalible: <?php echo $rows[$product_qua]; ?><br></td>
<td> - </td>
<td>Price: <?php echo $rows[$product_price]; ?><br></td>
<td> - </td>
<td>Description: <?php echo $rows[$product_des]; ?><br></td>
</tr>
<?php endwhile; ?>
</table>
Tip: I prefer to use the while/endwhile; approach rather than using brackets when displaying data to the user.
First of all don't echo so much HTML using PHP, instead do it like this
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
$sql = mysql_query("SELECT * FROM products"); ?>
<table id='display'>
<?php
while($rows = mysql_fetch_array($sql)) {
?>
<tr><td><?php echo $rows[$product_name]; ?></td>
<!-- And so on-->
<?php
}
?>
</table>
Secondly by seeing your inmage, it seems like you need a border for your table so use
table, td {
border: 1px solid #000000;
}
add the following css to apply border on your table cells:
#display td{ border: 2px solid red; }
and optionally add to your #display { :
border-collapse: collapse;

Mysql data to a styled HTML Table

I need some Help. I'm new to PHP and the last couple of days trying to solve this issue. I am trying to parse data from my database to a styled HTML Table and I am not able to find any tutorials on this. I did do the tutorial for parsing to a table that is created with PHP. I would like to use the tables I did include in this file. If anyone would be so kind to show me how to do this and also explain it I would be very happy.
This is the PHP file I did try to work with. Only one close I could find from tutorials.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("tegneserier") or die(mysql_error());
// Get all the data from the "årgang" table
$result = mysql_query("SELECT * FROM årgang")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Navn</th> <th>Årgang</th> <th>NR</th> <th>Navn</th> <th>Navn</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td><td>";
echo $row['issue'];
echo "</td><td>";
echo $row['Description'];
echo "</td><td>";
echo $row['quality'];
echo "</td></tr>";
}
echo "</table>";
?>
This is the stylesheet I would like to use:
/* ------------------
styling for the tables
------------------ */
body
{
line-height: 1.6em;
}
#hor-zebra
{
font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
font-size: 12px;
margin: 60px;
width: 480px;
text-align: left;
border-collapse: collapse;
}
#hor-zebra th
{
font-size: 14px;
font-weight: normal;
padding: 10px 8px;
color: #039;
}
#hor-zebra td
{
padding: 8px;
color: #669;
}
#hor-zebra .odd
{
background: #e8edff;
And this is the HTML file where I would like the data from my database to show:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DataTable Output</title>
<style type="text/css">
<!--
#import url("style.css");
-->
</style>
</head>
<body>
<?php include("datamodtagelse.php"); ?>
<table id="hor-zebra" summary="Datapass">
<thead>
<tr>
<th scope="col">name</th> //Name off table in DB
<th scope="col">age</th> //Name off table in DB
<th scope="col">issue</th> //Name off table in DB
<th scope="col">Description</th> //Name off table in DB
<th scope="col">quality</th> //Name off table in DB
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr class="odd">
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr class="odd">
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</tbody>
</table>
</body>
</html>
After adding the code my PHP do return the result. The only problem is it it not showing my styled tables from my style.css and I also get the error "
Notice: Undefined variable: i in C:\Program Files (x86)\EasyPHP-5.3.9\www\Tables\Datamodtagelse.php on line 25
And under that it returns my output: (This is the php page.)
name age issue Description quality
Anders And & Co. 1949 1 Dette er en beskrivelse af en tegneserie. Very Fine.
When I open my html file it doesn't display anything at all.
I will add my file :
Datamodtagelse.php
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("tegneserier") or die(mysql_error());
// Get all the data from the "årgang" table
$result = mysql_query("SELECT * FROM årgang")
or die(mysql_error());
echo '<table id="hor-zebra" summary="Datapass">
<thead>
<tr>
<th scope="col">name</th>
<th scope="col">age</th>
<th scope="col">issue</th>
<th scope="col">Description</th>
<th scope="col">quality</th>
</tr>
</thead>
<tbody>';
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
if( $i++ % 2 == 0 ) {
$class = " class='odd'";
} else {
$class = "";
}
// Print out the contents of each row into a table
echo "<tr" . $class . "><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td><td>";
echo $row['issue'];
echo "</td><td>";
echo $row['Description'];
echo "</td><td>";
echo $row['quality'];
echo "</td></tr>";
}
echo "</tbody></table>";
?>
Showcomic.html:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DataTable Output</title>
<style type="text/css">
<!--
#import url("style.css");
-->
</style>
</head>
<body>
<?php include("datamodtagelse.php"); ?>
</body>
</html>
Style.css
body
{
line-height: 1.6em;
}
#hor-zebra
{
font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
font-size: 12px;
margin: 60px;
width: 480px;
text-align: left;
border-collapse: collapse;
}
#hor-zebra th
{
font-size: 14px;
font-weight: normal;
padding: 10px 8px;
color: #039;
}
#hor-zebra td
{
padding: 8px;
color: #669;
}
#hor-zebra .odd
{
background: #e8edff;
}
My database name is: tegneserier
My table in the database is: årgang
My attributes in the table is:
id int(11) AUTO_INCREMENT
name varchar(255) utf8_danish_ci
age int(11)
issue int(11)
Description text utf8_danish_ci
When looking at the code I think the problem is the HTML file nor importing the stylesheet and the data from the .php file?
The .php file and the .css file and the .html file is located in the same folder.
Any help is welcome.
And sorry this is probably just a easy beginner mistake. (We all need to start somewhere.)
Try something like this:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("tegneserier") or die(mysql_error());
// Get all the data from the "årgang" table
$result = mysql_query("SELECT * FROM årgang")
or die(mysql_error());
echo '<table id="hor-zebra" summary="Datapass">
<thead>
<tr>
<th scope="col">name</th> //Name off table in DB
<th scope="col">age</th> //Name off table in DB
<th scope="col">issue</th> //Name off table in DB
<th scope="col">Description</th> //Name off table in DB
<th scope="col">quality</th> //Name off table in DB
</tr>
</thead>
<tbody>';
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
if( $i % 2 == 0 ) {
$class = " class='odd'";
} else {
$class = "";
}
// Print out the contents of each row into a table
echo "<tr" . $class . "><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td><td>";
echo $row['issue'];
echo "</td><td>";
echo $row['Description'];
echo "</td><td>";
echo $row['quality'];
echo "</td></tr>";
}
echo "</tbody></table>";
?>
And in your HTML file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DataTable Output</title>
<style type="text/css">
<!--
#import url("style.css");
-->
</style>
</head>
<body>
<?php include("datamodtagelse.php"); ?>
</body>
</html>
you are almost there (if the code you showed us runs).
in your php file, you need to give your table the id "hor-zebra", so that the style will be applied to it and the th's and td's within it.
you also want to add a counter to get the .odd thing right:
var $i = 0;
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr";
if( $i++ % 2 == 0 ) echo(" class='odd'");
echo "><td>";
...
you also might want to set the scope="col" in your th's to match the original table as closely as possible
AND last but not least: Don't forget the elements thead and tbody in your echo-output.
if you do all this, you should see the same table twice in your final html (check the source, ctrl+U)
Remember you can echo your data in div tags too, use
<li></li>
to allow row after row of sql data to get displayed. I mention this because I find the div elements easier to work with than tables.

How to sort rows of HTML table that are called from MySQL

I know it's such a basic thing, but a Google search hasn't shown me how to re-sort the rows after clicking the th links.
I've got this:
<table border="1">
<tr>
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
</tr>
<?php
while($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['description'] ?></td>
<td><?php echo $row['recorded_date'] ?></td>
<td><?php echo $row['added_date'] ?></td>
</tr>
<br />
<?php
}
mysql_close();
?>
</table>
I need to be able to click type and sort alphabetically, and click on either Recorded Date or Added Date and sort by date. I see that I need to have the MySQL queries do this, but do I set them up as conditionals with a href tags?
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
That's actually pretty easy, here's a possible approach:
<table>
<tr>
<th>
Type:
</th>
<th>
Description:
</th>
<th>
Recorded Date:
</th>
<th>
Added Date:
</th>
</tr>
</table>
<?php
$orderBy = array('type', 'description', 'recorded_date', 'added_date');
$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
$query = 'SELECT * FROM aTable ORDER BY '.$order;
// retrieve and show the data :)
?>
That'll do the trick! :)
A SIMPLE TABLE SORT PHP CODE:
(the simple table for several values processing and sorting, using this sortable.js script )
<html><head>
<script src="sorttable.js"></script>
<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>
<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');
if (!empty($_POST['myFirstvalues']))
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
?>
</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>
The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>
<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default; position:relative;">
<tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>
<?php
foreach($First as $indx => $value) {
echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL = <b>111111111</b></td><td>Still to spend = <b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>
source: php sortable table
//this is a php file
<html>
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
<script type="text/javascript">
function working(str)
{
if (str=="")
{
document.getElementById("tump").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tump").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsort.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body bgcolor="pink">
<form method="post">
<select name="sortitems" onchange="working(this.value)">
<option value="">Select</option>
<option value="Id">Id</option>
<option value="Name">Name</option>
<option value="Email">Email</option>
<option value="Password">Password</option>
</select>
<?php
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine");
echo "<center><br><br><br><br><table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table></center>";?>
</form>
<br>
<div id="tump"></div>
</body>
</html>
------------------------------------------------------------------------
that is another php file
<html>
<body bgcolor="pink">
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
</head>
<?php
$q=$_GET['q'];
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine order by $q");
echo "<table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table>";?>
</body>
</html>
that will sort the table using ajax
This is the most simple solution that use:
// Use this as first line upon load of page
$sort = $_GET['s'];
// Then simply sort according to that variable
$sql="SELECT * FROM tracks ORDER BY $sort";
echo '<tr>';
echo '<td>Title<td>';
echo '<td>Album<td>';
echo '<td>Artist<td>';
echo '<td>Count<td>';
echo '</tr>';
It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY. I would like to suggest javascript alternatives.
In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)
Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22 you will get 1, 11, 2, 22.
You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table> in HTML5 has sortable attribute, but apparently it's not implemented yet.

Categories