I know i post a lot of problems lately, but this one problem which i couldn't solve for about 1 week, I tried million times to check if data exists but still nothing. Searched, checked same problem but didn't get a hint. So please tell me what is wrong here. I try everything on my own but if i meet a problem i can't solve for a while. I ask here for help.
<!DOCTYPE html>
<html>
<head>
<title>Test Title</title>
</head>
<body>
<?php
class Database{
public $db;
public function __construct($host,$username,$password,$dbname){
$this->db=new MySQLi($host,$username,$password,$dbname);
}
public function getData(){
$query="SELECT * FROM artisan";
$result=$this->db->query($query);
$users=array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$users[]=array(
"id"=>$row['id'],
"username"=>$row['username'],
"email"=>$row['email']
);
}
}else{
echo "No results found!";
}
return $users;
}
public function getContent(){
$query="SELECT * FROM content";
$result=$this->db->query($query);
$values=array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$values[]=array(
"title"=>$row['title'],
"body"=>$row['body']
);
}
}
return $values;
}
public function insertData(){
$title=$_POST['title'];
$query="INSERT INTO content(title,body) VALUES (?,?)";
$result=$this->db->query("SELECT COUNT(*) FROM content WHERE title=$title");
$stmt=$this->db->prepare($query);
$stmt->bind_param("ss",$_POST['title'],$_POST['body']);
if(!empty($_POST['title']) || !empty($_POST['body'])){
if($result->num_rows){
echo "User allready exists";
}else{
$stmt->execute();
}
}
}
private function validate(){
$query="SELECT title and body FROM contents";
$result=$this->db->query($query);
if($result){
echo "hi";
}
}
}
$database=new Database('localhost','root','','test');
$users=$database->getData();
$values=$database->getContent();
$database->insertData();
?>
<style type="text/css">
.container{
text-align:center;
}
table, th, td, {
border: 1px solid black;
}
table{
width:100%;
}
.content{
border:1px solid black;
}
</style>
<div class="container">
<?php
for($i=0;$i<count($values);$i++):
?>
<div class="content">
<?php echo $values[$i]["title"]."<br>"; ?>
<?php echo $values[$i]["body"]."<br>";?>
</div>
<?php endfor;?>
</div>
<table>
<colgroup>
<col span="2" style="background-color:red">
<col style="background-color:yellow">
</colgroup>
<tr>
<th>ID</th>
<th>username</th>
<th>email</th>
</tr>
<tr>
<td><?php foreach($users as $user)
echo $user['id']."<br>";
?></td>
<td><?php foreach($users as $user)
echo $user['username']."<br>";
?></td>
<td><?php foreach($users as $user)
echo $user['email']."<br>";
?></td>
</tr>
</table>
<form action="index.php" method="POST">
<input type="text" name="title">
<input type="text" name="body">
<input type="submit" name="submit">
</form>
</body>
</html>
"$result=$this->db->query("SELECT title FROM content WHERE title='$title'"); just changed everything to this and it worked,$result was returning false,so i tried to solve it but i guess adding ' ' to $title solved idk why. – DummyTarget 12 mins ago"
That's because $title is a string literal and it needs to be quoted. You really should use a prepared statement for everything though, and will help safeguard against a potential SQL injection.
Reference:
https://dev.mysql.com/doc/refman/5.5/en/string-literals.html
Debugging:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Related
I'm retrieving all the rows from sql database through a query, and i'm using a loop to get all the rows
I have a style.css file which i'm specifying a style for the , however, only the first row is receiving the style and the style is not being applied to the rest.
<!DOCTYPE html>
<html>
<link href="styles.css" rel="stylesheet">
<head>
<title>IIACSS search center</title>
</head>
<body>
<form method="post">
<label>Search</label>
<input type="text" name="search">
<input type="submit" name="submit">
</form>
<?php
$con = new PDO("mysql:host=localhost;dbname=data",'root','admin123');
if (isset($_POST["submit"])) {
$str = $_POST["search"];
$sth = $con->prepare("SELECT * FROM `questions` WHERE question LIKE '%$str%'");
$sth->setFetchMode(PDO:: FETCH_OBJ);
$sth -> execute();
?>
<table>
<tr>
<th>Project</th>
<th>Question</th>
<th>Sample</th>
</tr>
<?php
for ($a=0;$row = $sth->fetch();$a++) {
?>
<tr>
<td><?php echo $row->Proj_Name; ?></td>
<td><?php echo $row->Question;?></td>
<td><?php echo $row->sample;?></td>
<br><br>
</tr>
</table>
<?php
}
}
?>
body {
background-color: white;
}
h1 {
color: black;
}
td {
color: black;
font-family: sans-serif;
}
th {
color: blue;
font-family: sans-serif;
}
It is not a CSS problem, it is because you are closing your </table> in the loop, so it is ending your table after the first tr.
Just remove it from the loop:
<?php
$con = new PDO("mysql:host=localhost;dbname=data",'root','admin123');
if (isset($_POST["submit"])) {
$str = $_POST["search"];
$sth = $con->prepare("SELECT * FROM `questions` WHERE question LIKE '%$str%'");
$sth->setFetchMode(PDO:: FETCH_OBJ);
$sth -> execute();
?>
<table>
<tr>
<th>Project</th>
<th>Question</th>
<th>Sample</th>
</tr>
<?php
for ($a=0;$row = $sth->fetch();$a++) {
?>
<tr>
<td><?php echo $row->Proj_Name; ?></td>
<td><?php echo $row->Question;?></td>
<td><?php echo $row->sample;?></td>
<br><br>
</tr>
<?php
} ?>
</table>
<?php }
?>
I am just self-learning PHP and SQL. This question seems repetitive, but I cannot find exact solution for my problem.
I have a SQL database for inventory management of mobile phones. I have implemented PHP script to display the database contents in a table. I have to further enhance the script, so the user can change the status of the mobile phone such as Working or Not working. For this I have created another SQL database storing this info. I am able to display the details in a dropdown, but when I change from Working to Not working and select Submit button, no change is seen in the database and also in the web server.
<?php
$servername="localhost";
$username="root";
$password="XXXXX";
$dbname="inventory_db";
//Connection
$conn =mysqli_connect($servername,$username,$password);
$db_handle = $conn->select_db($dbname);
//Connection check
if($conn->connect_error)
{
die("Connection failed:" .$conn->connect_error);
}
else {
echo "connection setup";
}
if($db_handle)
{
$sql="SELECT asset_no,asset_name,current_holder,location,status FROM Phone_table ";
$sql_status="SELECT idstatus,status_name FROM status_table";
?>
<!DOCTYPE html>
<HTML>
<HEAD>
<STYLE>
.asset_table
{
width: 100%;
border :1px solid black;
}
td{
text-align: left;
padding: 15px;
border: 1px solid black;
}
th{
border: 1px solid black;
}
</STYLE>
</HEAD>
<BODY>
<form method="post">
<TABLE class="asset_table">
<TR>
<TH>Asset Number</TH>
<TH>Asset Name</TH>
<TH>Asset Holder</TH>
<TH>Location</TH>
<TH>Status</TH>
</TR>
<?php
$result=$conn->query($sql);
$count=mysqli_num_rows($result);
if($result->num_rows > 0)
{
while($row=$result->fetch_assoc())
{?>
<TR>
<TD> <?php echo $row['asset_no']; ?> </TD>
<TD> <?php echo $row['asset_name']; ?></TD>
<TD> <?php echo $row['current_holder']; ?></TD>
<TD> <?php echo $row['location']; ?></TD>
<TD><select>
<?php
<!-- *****This is where I am stuck*****-->
$result_status=$conn->query($sql_status);
if($result_status->num_rows > 0)
{
while($row_status=$result_status->fetch_assoc())
{ ?>
<option value =' <?php echo $row_status['idstatus']?> '>
<?php echo $row_status['status_name'];?> </option>
<?php $row['status']=$row_status['status_name'];
}} ?></select>
</TD>
</TR>
<?php
}}?>
<input type="submit">
</form>
<?php
if($submit)
{
for($i=0;$i<$count;$i++)
{
$sql="UPDATE Phone_table SET status='$status[$i]' WHERE asset_no='$asset_no[$i]'";
$result=$conn->query($sql);
}
}
?>
</TABLE>
</BODY>
</HTML>
<?php }
ob_end_flush(); ?>
One problem with the existing code is that there was no way to relate the submitted value for the asset status ( even if it had been given a name! ) to the particular record in the database. The update statement would require, usually, an ID in the where clause so that the releveant record can be updated as opposed to ALL records being updated equally. To that end, given the HTML structure and generaly approach ( no javascript & single form ) using a hidden input field for each row in the table to hold the record ID seems to make sense. When the form is submitted the value for the select menu and the id should be relatable - you will see by the demo below.
Because there is a single form with multiple records the select menu and the hidden input will need to be treatable as arrays - that is to say their names should be of the form name[]
Another thing to note perhaps is the use of variables directly within the sql. This practise leaves your code vulnerable to sql injection and whilst this may be on a closed system somewhere with trusted users etc you never know what might happen!
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
/* connect to the db */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'inventory_db';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* declare the sql statements for later use */
$sql=(object)array(
'phones' => 'select `asset_no`, `asset_name`, `current_holder`, `location`, `status` from `phone_table`',
'status' => 'select `idstatus`, `status_name` from `status_table`',
'update' => 'update `phone_table` set `status`=? where asset_no=?'
);
/* very basic utility function to generate select menu */
function createselect( $name, $data, $value ){
$html=array();
$html[]=sprintf( '<select name="%s">', $name );
foreach( $data as $id => $status ){
$selected = $id == $value ? ' selected=true' : '';
$html[]=sprintf('<option value="%s"%s>%s', $id, $selected, $status );
}
$html[]='</select>';
return implode( PHP_EOL, $html );
}
/* query database to get possible status values which are used to create the SELECT menus */
$status=array();
$results=$db->query( $sql->status );
if( $results ){
while( $rs=$results->fetch_object() )$status[ $rs->idstatus ]=$rs->status_name;
}
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* using `user supplied data` - use a prepared statement to be safe! */
$stmt=$db->prepare( $sql->update );
$stmt->bind_param( 'ii', $assetstatus, $assetid );
/* Perform the update */
foreach( $_POST['id'] as $i => $assetid ){
$assetstatus = $_POST['status'][ $i ];
$stmt->execute();
}
$stmt->close();
exit( header( 'Location: ?db=updated' ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Asses or Assets?</title>
<style>
body{font-family:verdana}
table{ width: 100%; border :1px solid black; }
td{ text-align: left; padding: 15px; border: 1px solid black;text-align:center; }
th{ border: 1px solid black; }
input,select{padding:1rem;width:100%}
</style>
</head>
<body>
<?php
/* get the phones... no user input so no need for prepared statement */
$results = $db->query( $sql->phones );
if( $results ){
?>
<form method='post'>
<table>
<thead>
<tr>
<th>Asset Number</th>
<th>Asset Name</th>
<th>Asset Holder</th>
<th>Location</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
while( $rs = $results->fetch_object() ){
printf(
"<tr>
<td>%s<input type='hidden' name='id[]' value='%d' /></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>",
$rs->asset_no,
$rs->asset_no,
$rs->asset_name,
$rs->current_holder,
$rs->location,
createselect( 'status[]', $status, $rs->status )
);
}
?>
</tbody>
<tfoot>
<tr>
<td colspan=5>
<input type='submit' />
</td>
</tr>
</tfoot>
</table>
</form>
<?php
}//close `if`
?>
</body>
</html>
In general the form creation/display and the acting upon the submitted form are two entirely unrelated HTTP requests.
You have to change a few things to get your script to work:
1. Add a hidden field for each asset no.:
<TD>
<input type="hidden" name="asset_no[]" value="<?php echo $row['asset_no']; ?>">
<?php echo $row['asset_no']; ?>
</TD>
2. Add name attribute to your select fields:
<TD><select name="asset_status[]">
3. Make your select fields preselect the current status and remove the whitespace in the value:
<option value ='<?php echo $row_status['idstatus'] ?>' <?= $row['status'] == $row_status['idstatus'] ? ' selected' : '' ?>>
4. Remove this statement, as it does nothing (you're not writing to the array you read from the database):
$row['status']=$row_status['status_name'];
5. Add a name property to your submit field:
<input type="submit" name="submit">
6. Read your submitted form from the superglobal array $_POST (see php.net):
if(isset($_POST['submit']))
{
for($i=0;$i<count($_POST['asset_no']);$i++)
{
$asset_status = mysqli_real_escape_string($conn, $_POST['asset_status'][$i]);
$asset_no = mysqli_real_escape_string($conn, $_POST['asset_no'][$i]);
$sql = "UPDATE Phone_table SET status='$asset_status' WHERE asset_no='$asset_no'";
$result = $conn->query($sql);
}
}
I have this php code with a drop down pulling info from the database but cannot seem to figure out how to get the drop down selection to sort the list...
The drop down is showing the course name as the label but when selected needs to sort the list by course id.
Visit Here to see the table in action
<?php
$connect = mysql_connect('localhost','emscompl_paramed','PASSOWRD) or die(mysql_error());
$selectdb = mysql_select_db('emscompl_joom1283',$connect);
$sel = "SELECT us.fullname, s . *
FROM registered_users AS `us`
LEFT OUTER JOIN course_students AS s ON s.userid = us.userid";
$ressel = mysql_query($sel);
$fetchsel = mysql_fetch_array($ressel);
?>
<!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>Untitled Document</title>
<style type="text/css">
.titiel {
font-weight: bold;
}
td {
border-right-width: thin;
border-bottom-width: thin;
border-right-style: dotted;
border-bottom-style: solid;
text-align:center;
}
th {
background-color:#000000;
color: #FFF;
}
tr:nth-child(odd) { background-color:#eee; }
tr:nth-child(even) { background-color:#fff; }
</style>
</head>
<body>
<p class="titiel">Pre-Entrance Document Report</p>
<p> Please Select Course for Report</p>
<form method="post" action="preentrancereportsorted.php">
<label for="select"><select name="course" value="Select" size="1">
<?php
$sql = "SELECT * FROM courses";
$result = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($result))
{
$id=$row["id"];
$course=$row["coursename"];
$options.="<OPTION VALUE=\"$id\">".$course;
}
?>
<option>
<? echo $options ?>
</option>
</select>
<input type="submit" name="Submit" value="Generate Report">
</form>
<table width="1246" height="56">
<tr>
<th width="147" height="50">Student Name</td>
<th width="15">R</th>
<th width="18">M</th>
<th width="18">L</th>
<th width="81">Background</th>
<th width="83">Drug Screen</th>
<th width="112">Clear Background</th>
<th width="113">Clean Drug Screen</th>
<th width="97">Student Info</th>
<th width="88">School App</th>
<th width="117">Professional Recomendation</th>
<th width="119">Reasonable Accomadations</th>
<th width="59">Drivers Licesnse</th>
<th width="91">High School Diploma</th>
</tr>
<?php while ($row = mysql_fetch_array($ressel)) { ?>
<td width="146" height="50"><?php echo $row['fullname'];?></td>
<td width="17"><?php echo $row['entrancereadingscore'];?></td>
<td width="17"><?php echo $row['mathscore'];?></th>
<td width="17"><?php echo $row['locatinginfoscore'];?></td>
<td width="84"> <?php echo $row['backcalc'];?></td>
<td width="79"><?php echo $row['drugcalc'];?></td>
<td width="113"><?php if ($row['clearbackground']='1')
{
echo "Yes";
}
else
{
echo "no";
}
?></td>
<td width="114">
<?php if ($row['cleardrugtest']=='1')
{
echo "Yes";
}
else
{
echo "No";
}
?>
</td>
<td width="96">
<?php if ($row['studentinformationsheet']=='1')
{
echo "Yes";
}
else
{
echo "No";
}
?>
</td>
<td width="89">
<?php if ($row['schoolapplication']=='1')
{
echo "Yes";
}
else
{
echo "No";
}
?>
</td>
<td width="118">
<?php if ($row['professionalreco']=='1')
{
echo "Yes";
}
else
{
echo "No";
}
?>
</td>
<td width="119">
<?php if ($row['reasonableaccom']=='1')
{
echo "Yes";
}
else
{
echo "No";
}
?>
</td>
<td width="58">
<?php if ($row['driverlicesnce']=='1')
{
echo "Yes";
}
else
{
echo "No";
}
?>
</td>
<td width="91">
<?php if ($row['highschooldip']=='1')
{
echo "Yes";
}
else
{
echo "No";
}
?>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
If you want to sort your select box by id, then definitely use "ORDER BY" as Pachonk says above.
Also, I've noticed that your PHP below:
<option>
<? echo $options ?>
</option>
is outputting:
<option>
<option value="Some id">some text
<option value="some other id">some other text
... repeat for all options
</option>
You should remove the first from around the PHP (you are placing an tag in the php echo statement anyway) and place the tag in your php code above so that every has an
like:
$result = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($result))
{
$id=$row["id"];
$course=$row["coursename"];
$options.="<OPTION VALUE=\"$id\">".$course . "</option>";
^^^^^^^^^^^^^ added these
}
?>
// removed <option>
<? echo $options ?>
// removed </option>
</select>
Of course, you could just have the php in the while clause output your option right there and then too.
Hope that helps in some way.
I have a results page and I would like there to be a bit at the top of the page where it says how many results were returned. How do I do this?
My code is
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("3", "", "");
mysql_select_db ("");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,location,msg FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result) {
while ($row = mysql_fetch_array ($result)) { ?>
<center>
<table height="20" width="968" cellpadding="0" cellspacing="0">
<tr>
<td>
<table height="20" width="223" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="#045FB4"><?php echo $row[0]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
<td>
<table height="20" width="745" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="black"><?php echo $row[1]; ?>
<?php echo $row[2]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
<td align="right">
<font face="helvetica" size="2" color="red">See More...</font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
</tr>
</table>
<?php
}
}
}
?>
</center>
THANKS!
James
If you're going to keep it to one page then mysql_num_rows() will do the trick and you're good to go. If you use pagination on the other hand, then your SELECT query will have a LIMIT clause and a second query can be constructed using COUNT(*) on the same tables with the same WHERE clause.
$total_query = "SELECT COUNT(*) FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'"
I’m not trying to compete with the other fine answers. I’m posting this as an answer because it’s too big for a comment.
Since you asked in a comment what could be done to improve your HTML, I refactored your code a bit just to illustrate some things you could do. I also included mysql_num_rows($result) mentioned by the others for the sake of completion.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
<style type="text/css">
table {
font-family: helvetica;
font-size: small;
width: 968px;
}
td {
border-bottom: 1px solid #e6e6e6;
}
.name {
color:#045FB4;
}
.msg {
color:black;
}
.more {
color:red;
}
</style>
</head>
<body>
<?php
if(strlen(trim($_POST['search'])) > 0):
$search = mysql_real_escape_string($_POST["search"]);
$searchterm = mysql_real_escape_string($_POST["searchterm"]);
mysql_connect ("localhost", "root", "");
mysql_select_db ("sample");
if (!empty($_POST["search_string"]))
{
$search_string = mysql_real_escape_string($_POST["search_string"]);
// more code here
}
$query = "SELECT name,location,msg FROM contact
WHERE name LIKE '%$search%'
AND location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result):
$num_rows = mysql_num_rows($result);
?>
<p>Found <?php echo $num_rows; ?> results.</p>
<table>
<?php
while ($row = mysql_fetch_array ($result)):
?>
<tr>
<td class="name"><?php echo $row['name']; ?></td>
<td class="msg"><?php echo $row['location'], ' ', $row['msg']; ?></td>
<td class="more">See More...</td>
</tr>
<?php
endwhile;
endif;
endif;
?>
</table>
</body>
</html>
Normally, I would put the CSS in a separate file, but this is only an example.
Some things to notice:
There’s only one table
There’s no style information in the HTML
It uses mysql_real_escape_string. Ideally you'd also want to use prepared statements, but I’ll leave that as a personal exercise for you. :)
Even this can be improved quite a bit, but it's a start.
Try using mysql_num_rows($query). I am no PHP expert but, from memory, that should do the trick. Just echo this wherever you want it.
$num_rows = mysql_num_rows($result);
Check out the documentation: http://php.net/manual/en/function.mysql-num-rows.php
Also you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
$query = "SELECT SQL_CALC_FOUND_ROWS name,location,msg FROM contact WHERE name LIKE '%$search%' AND location LIKE '%$searchterm%'";
$result = mysql_query($query);
if ($result)
{
$rs_count = mysql_query("SELECT FOUND_ROWS();");
$counted = (int)mysql_result($rs_count, 0);
}
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.