1

I have a database called forms1 and a table named demo
The fields in the table are ID, Autore, Titolo, cit

I wish I had a first line that gives me the ability to sort alphanumeric values ​​that are retrieved by the query.
For sort i mean this:
How to sort rows of HTML table that are called from MySQL

My problem is adapt code for my situation. This is cerca2.php:

<style>
br {margin-bottom:-10px;}
</style>

<form action="cerca2.php" method="post">
<b>Nome</b>&nbsp;<input type="text" name="Nome">&nbsp;&nbsp;
<b>Numero&nbsp;</b><input type="text" name="Numero">&nbsp;&nbsp;
<b>city&nbsp;</b><input type="text" name="city">&nbsp;&nbsp;
<input type="Submit">
</form>

<style>
tr:nth-of-type(odd) { background-color: AZURE; }
tr:nth-of-type(even) { background-color: CYAN; }
</style>
<style>
tr:hover{background-color:DEEPSKYBLUE;}
</style>

<?php

echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";  
echo "<tr style='font-weight: bold;'>";  
echo "<td width='auto' bgcolor=”#7FFFD4″>&nbsp;<i>ID<i/></td>";  
echo "<td width='auto' >&nbsp;<i>Nome<i/></td>";
echo "<td width='auto' ></td>";
echo "<td ></td>";
echo "</tr>";

define('DB_NAME', 'forms1');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) {
    die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}

$Nome = str_replace(' ', '%', $_POST['Nome']);
$Numero = str_replace(' ', '%', $_POST['Numero']); 
$city = str_replace(' ', '%', $_POST['city']); 

$arNome = str_split($Nome);
$arNumero = str_split($Numero);
$arcity = str_split($city);

$Nome='';
foreach ($arNome as $value) 
{
   if ($value=='%') continue;
   $Nome.=$value.'%';

}

$Numero='';
foreach ($arNumero as $value) 
{
   if ($value=='%') continue;
   $Numero.=$value.'%';

}

$city='';
foreach ($arcity as $value) 
{
   if ($value=='%') continue;
   $city.=$value.'%';

}

$sql = mysql_query("SELECT * FROM demo WHERE Autore LIKE '%$Nome%' AND Titolo LIKE '%$Numero%' AND cit LIKE '%$city%' ORDER BY Autore") or die(mysql_error());


$i = 0; while($row=mysql_fetch_array($sql)){
        $i++;
        echo "<tr>";
        echo "<td width='auto' bgcolor=”#FF0000 &#8243;>" . "&nbsp;". "<b>"  . $i . "&nbsp;". "<b/>". "</td>";
        echo "<td width='auto'>" . "&nbsp;" . $row[1] . "&nbsp;" . "</td>";
        echo "<td width='auto'>". "</td>";
        echo "<td width='auto'>" . "&nbsp;". "<i>" . $row[2] . "<i/>". "&nbsp;" . "</td>";     
        echo "<td width='auto'>" . "&nbsp;". "<i>" . $row[3] . "<i/>". "&nbsp;" . "</td>";
        echo "</tr>";

}

mysql_close();
?>
Community
  • 1
  • 1
user143822
  • 237
  • 2
  • 9
  • What do you mean by "sort alphanumeric values ​​that are retrieved by the query"? What values? Are you trying to sort results returned by the query? Are you trying to sort within the query itself (you're already sorting by Autore)? – user428517 Oct 19 '12 at 13:49
  • **Are you trying to sort within the query itself** yes, like this http://stackoverflow.com/questions/3489783/how-to-sort-rows-of-html-table-that-are-called-from-mysql but how must adapt code for my situation? – user143822 Oct 19 '12 at 13:53

3 Answers3

1

If you're looking for a Javascript solution tablesorter would do the job. Handy and easy.

EDIT
At the very top add :

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://tablesorter.com/__jquery.tablesorter.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){ $("table").tablesorter(); });
</script>

http://pastebin.com/dLJqJQuX

Touki
  • 7,465
  • 3
  • 41
  • 63
  • 1
    I try but i don't undestand tablesorter, i don't know how must it include inside my code. Can u help me, please? – user143822 Oct 19 '12 at 13:50
  • @user143822 Check edition. This would do the job quickly. You may have a look at [jQuery](http://jquery.com) to understand better what i've done. – Touki Oct 19 '12 at 13:54
  • This looks like a good JavaScript solution. @user143822 if you want to do this in PHP it's going to involve a lot more work. You'd want to make your table headers clickable links that set a $_GET parameter which you'll use to sort by as per Alexey Sidorov's answer. – user428517 Oct 19 '12 at 13:56
  • @user143822 I guess that's because you forgot `` Try this full code : http://pastebin.com/dLJqJQuX – Touki Oct 19 '12 at 14:15
  • Edition: You need a `` in your table headers instead of ``'s – Touki Oct 19 '12 at 14:20
  • i try your code but nothing change look this pic, please http://imageshack.us/a/img209/2514/columnd.png – user143822 Oct 19 '12 at 14:40
1

You should include LIMIT to your sql query, so you have to sort not only data you have already printed, and the hidden.

In your case try to reload page and use $_GET['name_sort'] to change your sql

if ($_GET['name_sort'] == 'desc') {
    $sql = mysql_query("SELECT * FROM demo WHERE Autore LIKE '%$Nome%' AND Titolo LIKE '%$Numero%' AND cit LIKE '%$city%' ORDER BY Autore DESC") or die(mysql_error());

} else {

    $sql = mysql_query("SELECT * FROM demo WHERE Autore LIKE '%$Nome%' AND Titolo LIKE '%$Numero%' AND cit LIKE '%$city%' ORDER BY Autore ASC") or die(mysql_error());
}
Alexey Sidorov
  • 846
  • 1
  • 9
  • 17
0

If you want a sortable table, I use the javascript library called "sortable" - it's easy to configure and use.

EDIT showing example HTML: This HTML expects the "sortable.js" file to be in the same directory as the HTML file:

<html>
  <head>
    <script type="text/javascript" src="sortable.js"></script>
  </head>
  <body>
    <h1>Test Table</h1>
    <table id="myTable" class="sortable">
      <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
      </tr>

      <tr>
        <td>1</td>
        <td>Hello</td>
        <td>10/01/2012</td>
      </tr>

      <tr>
        <td>2</td>
        <td>Goodbye!</td>
        <td>10/04/2011</td>
      </tr>

      <tr>
        <td>3</td>
        <td>Welcome</td>
        <td>22/09/1985</td>
      </tr>
    </table>
  </body>
</html>
GarethL
  • 1,473
  • 1
  • 15
  • 16
  • read the link in my answer. It explains step-by-step how to implement the solution. If language is a problem, I speak Italian. – GarethL Oct 19 '12 at 14:08
  • si parlo anche io in italiano, mi daresti un a mano? Ho provato la soluzione sopra la tua, quella di Alexey Sidorov, ma mi cambia nulla – user143822 Oct 19 '12 at 14:17
  • Allora, devi scaricare prima lo script Javascript, come scritto nel link, poi lo devi includere nella sezione "HEAD" del tuo HTML, in questo modo: ``. Aggiungi un class CSS `"sortable"` alla tabella, e a quel punto, fa tutto lo script. ENGLISH: You need to download the javascript, as in the link I linked to, then you need to add it to you HTML HEAD section, so: ``. You need to add a `"sortable"` class to table, and the script does the rest. – GarethL Oct 19 '12 at 14:33
  • Se vuoi un esempio di come funziona questo script, vai al sito di Fabriano Rugby (google), e guarda la sezione "statistiche". La tabella che vedi usa esattamente questo script "sorttable". – GarethL Oct 19 '12 at 14:44
  • ho provato ma niente. Ho scritto così: http://pastebin.com/E7Bf4P6K guarda anche l'immagine http://imageshack.us/a/img839/5231/error2we.png – user143822 Oct 19 '12 at 14:55
  • Purtroppo sono in ufficio, e quei siti sono bloccati dal proxy. Adesso aggiorno la mia risposta con del codice più completo. – GarethL Oct 19 '12 at 14:57
  • Ho provato ma il problema è che devo implementare il tutto con il php. L'immagine la puoi vedere qui: http://stackoverflow.com/questions/12974176/sort-sql-query-id-reset-and-start-in-numerical-order-every-time-i-make-a-query Praticamente io ho dei form che uso per interrogare il database e quando ho i risultati (nella stesa pagina php) visualizzo le cose in una tabella. Come si fa a implementare il tuo codice e lo script javascript coi comandi echo? Io infatti "stampo" la tabella col php. Il tuo script mi servirebbe per rendere sortable ogni colonna. – user143822 Oct 19 '12 at 15:24
  • Ma non c'è bisogno di farlo, e quello che ti sto dicendo. Devi fare un echo per produrre l'HTML, no? A quel punto, inserisci tra quegli echo un altro che abbia "" e modifica quello della definizione della tabella in e ci pensa lo script Javascript. Non ci sono "commandi" Javascript da scrivere, l'importante è che riesci a fare un echo che includa lo script nell'HEAD dell'HTML.
    – GarethL Oct 19 '12 at 16:07
  • pultroppo non so come fare. Io ho tentato, ma è troppo difficile. L'unico modo per capire è il codice completo. Mi riusciresti a fare questo favore? ho inserito questa domanda anche sul forum italiano. Con tablesorter sono andato molto vicino, ma ci sono problemi di formattazione. Guarda qui, ti prego http://forum.html.it/forum/showthread.php?s=&threadid=1525094 – user143822 Oct 19 '12 at 19:10