2010-08-15 20 views
15

So che è una cosa così fondamentale, ma una ricerca su Google non mi ha mostrato come riordinare le righe dopo aver fatto clic sui collegamenti th.Come ordinare le righe della tabella HTML chiamate da MySQL

ho questo:

<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> 

ho bisogno di essere in grado di fare clic type e ordinare in ordine alfabetico, e fare clic su entrambi Recorded Date o Added Date e ordina per data. Vedo che devo fare in modo che le query MySQL facciano questo, ma li ho configurati come condizionali con i tag a href?

risposta

37

Il modo più semplice per eseguire questa operazione consiste nel posizionare un collegamento sulle intestazioni delle colonne, puntando alla stessa pagina. Nella stringa di query, inserire una variabile in modo da sapere su che cosa hanno fatto clic e quindi utilizzare ORDER BY nella query SQL per eseguire l'ordine.

Il codice HTML sarebbe simile a questa:

<th><a href="mypage.php?sort=type">Type:</a></th> 
<th><a href="mypage.php?sort=desc">Description:</a></th> 
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th> 
<th><a href="mypage.php?sort=added">Added Date:</a></th> 

E nel codice php, fare qualcosa di simile:

<?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"; 
} 

$> 

Si noti che non si deve prendere il valore di $ _GET direttamente e aggiungere alla tua domanda. Come alcuni utenti potevano ottenere su MyPage.php? Sort =; ELIMINA DA MyTable;

+0

Hmm. Ricevo un errore Parse: errore di sintassi, T_IS_EQUAL inatteso per la prima istruzione 'if' – Joel

+1

Sì, probabilmente la mia sintassi non è perfetta. Penso che sia stato risolto ora. – Kibbee

+0

Non riesco a modificarlo da solo, ma ho trovato gli errori. Quello principale è che hai bisogno di $ sql non sql. Inoltre, i miei nomi delle tabelle sono diversi su un paio di colonne. Ma GRAZIE per aver fatto questo! Mi ha dato la risposta giusta! – Joel

38

Che in realtà è abbastanza facile, ecco una possibile approccio:

<table> 
    <tr> 
     <th> 
      <a href="?orderBy=type">Type:</a> 
     </th> 
     <th> 
      <a href="?orderBy=description">Description:</a> 
     </th> 
     <th> 
      <a href="?orderBy=recorded_date">Recorded Date:</a> 
     </th> 
     <th> 
      <a href="?orderBy=added_date">Added Date:</a> 
     </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 :) 
?> 

Basta così il trucco! :)

+0

Perché il voto di -1? modifica: -3 ..:/Perché !? –

+3

C'è sicuramente ** NO ** possibile iniezione SQL, guarda più vicino! Whitelist i campi possibili su cui ordinare. –

+1

Non ho votato a valle, ma per qualche ragione, non ricordo i controlli che sono stati lì quando ho visto la tua prima risposta. Tuttavia, potrei averlo perso, e anche altri potrebbero averlo perso. Mi piace il tuo stile meglio del mio, quindi ti sto dando anche un upvote. – Kibbee

1

A SEMPLICE tabella di ordinamento PHP CODICE:

(tabella semplice per l'elaborazione diversi valori e smistamento, usando questo script sortable.js)

<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 = &nbsp;<b>111111111</b></td><td>Still to spend = &nbsp;<b>5555555</b></td></tr></tfoot></br></br> 
</table> 
</body> 
</html> 

fonte: php sortable table

0
//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 
+0

Cosa succede se ho tabelle dinamiche per esempio. Ogni record o riga è una tabella diversa. Questa soluzione funzionerà per lo stesso? –

1

Questa è la soluzione più semplice che utilizza:

// utilizzare questo come prima linea su carico di pagina

$sort = $_GET['s']; 

// Poi basta sorta in base a quella variabile

$sql="SELECT * FROM tracks ORDER BY $sort"; 

echo '<tr>'; 
echo '<td><a href="report_tracks.php?s=title">Title</a><td>'; 
echo '<td><a href="report_tracks.php?s=album">Album</a><td>'; 
echo '<td><a href="report_tracks.php?s=artist">Artist</a><td>'; 
echo '<td><a href="report_tracks.php?s=count">Count</a><td>'; 
echo '</tr>'; 
0

Dipende dalla natura dei dati. La risposta varia in base alle dimensioni e al tipo di dati. Ho visto molte soluzioni SQL basate su ORDER BY. Vorrei suggerire alternative javascript.

In tutte le risposte, non vedo nessuno menzionare il problema dell'impaginazione per la tabella futura. Cerchiamo di renderlo più facile per te. Se la tua tabella non ha paginazione, è più probabile che una soluzione javascript renda tutto pulito e pulito per te dal lato client. Se pensi che questa tabella esploda dopo aver inserito i dati, devi pensare anche alla paginazione.(devi andare alla prima pagina ogni volta che cambi la colonna di ordinamento)

Un altro aspetto è il tipo di dati. Se usi SQL devi fare attenzione al tipo di dati e al tipo di suite di ordinamento per esso. Ad esempio, se in una delle tue colonne VARCHAR vengono memorizzati numeri interi, l'ordinamento non prenderà in considerazione il loro valore intero: anziché 1, 2, 11, 22 otterrai 1, 11, 2, 22.

È possibile trovare plug-in jquery o standalone javascript sortable tables su google. Vale la pena ricordare che lo <table> in HTML5 ha l'attributo sortable, ma a quanto pare non è ancora stato implementato.

Problemi correlati