jQuery table sorter does not sort my tables when I get data from MySQL

2

I apologize for the code, I'm learning, it's probably a disaster, but I can attest that the database connection does it well just like the query just that the script does not run correctly, I tried a table filled by hand without asking mysql and the script works without any problem, it just does not work when I run it with an SQL query.

Here is a GIF of how the code behaves when it is filled by hand with HTML at the top and how it behaves with an SQL query:

<?php
    session_start();
    require 'funcs/conexion.php';
    include 'funcs/funcs.php';

    if(!isset($_SESSION["id_usuario"])){ //Si no ha iniciado sesión redirecciona a index.php
        header("Location: index.php");
    }
    $idUsuario = $_SESSION['id_usuario'];

    $sql = "SELECT id, nombre FROM usuarios WHERE id = '$idUsuario'";
    $result123 = $mysqli->query($sql);
    $row123 = $result123->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="css/paginaadministrar.css">
    <link href="css/bootstrap-3.3.7.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="css/paginaadministrar.css">
    <link rel="stylesheet" type="text/css" href="css/nuevabarra.css">
    <link href='https://fonts.googleapis.com/css?family=Oswald:400,700' rel='stylesheet' type='text/css'>

    <script type="text/javascript" src="/login/js/libs/jquery-1.6.1.min.js"></script> 
    <script type="text/javascript" src="/login/js/libs/jquery.tablesorter.js"></script>
    <script type="text/javascript" src="/login/js/libs/jquery.tablesorter.combined.js"></script>

    <script type="text/javascript">
        $(document).ready(function() 
        { 
            $("#myTable").tablesorter(); 
        });
    </script>
    <script type="text/javascript">
        $(document).ready(function() 
        { 
            $("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} ); 
        });
    </script>
    <style type="text/css">
        a:link   
        {   
         text-decoration:none;   
        }   
    </style>
  </head>
  <body>
  <nav>
    <ul id="main">
        <li><a href='welcome.php' style='text-decoration:none;color:white;(otros)'>Inicio</a></li>
        <li>Eventos</li>
        <li><a href="perfil.php" style='text-decoration:none;color:white;(otros)'> Mi Perfil</a>
          <ul class="drop">
            <div>
            <li>Mis Reservaciones</li>
            <li>Mis Compras</li>
            <li><a href='logout.php' style='text-decoration:none;color:white;(otros)'>Cerrar Sesi&oacute;n</a></li>
            </div>
          </ul>
        </li>
        <li><a href='logout.php' style='text-decoration:none;color:white;(otros)'>Cerrar Sesi&oacute;n</a></li>
        <div id="marker"></div>
    </ul>
</nav>
<div align="center" class="main"> <!-- Primer Div Parallax -->
    <div align="center" class="container">
    <div class="felote"> <h2><font color="white"><?php echo ''.utf8_decode($row123['nombre']); ?></h1></font></div>
<!-- En esta area he creado un buscador para seleccionar el registro deseado -->   
<br><br/> <br/><br/><br/>     
<table width="600" border="0" cellpadding="3" cellspacing="1" align="center">
    <form method="POST" action="busqueda.php">
    <tr>
        <td colspan=2><p><strong>Usuarios Registrados :</strong>
            <input type="TEXT" name="valor_a_buscar" size="30" style="border: 1px solid #7F9DB7;">
            <input type="submit" value="BUSCAR" name="enviar">
            <p>(Introduzca el nombre de usuario)</p>
        </td>
    </tr>
    </form>
</table>

<!-- tablesorter fin -->
<!--Probar tabla de aqui-->

<table id='myTable' class='tablesorter'>
<tr>
    <td><font face="verdana1"><b>Usuario</b></font></td>
    <td><font face="verdana2"><b>Nombre</b></font></td>
    <td><font face="verdana3"><b>Correo</b></font></td>
</tr>       
<!-- En este espacio probare consulta de tabla INICIA-->
<?php   
    $link = @mysql_connect("localhost", "***","***")
      or die ("Error al conectar a la base de datos.");
        @mysql_select_db("login", $link)
      or die ("Error al conectar a la base de datos.");

    /*if(!isset($_SESSION["id_usuario"])){ //Si no ha iniciado sesión redirecciona a index.php
        header("Location: index.php");
    }

    $idUsuario = $_SESSION['id_usuario'];*/
    //Consulta tabla usuarios

    $query = "SELECT usuario, nombre, correo FROM usuarios";
    $result = mysql_query($query);
    $numero="0";

    while($row = mysql_fetch_array($result))
    {
        echo "<tr><td width=\"25%\"><font face=\"verdana1\">" . 
        $row["usuario"] . "</font></td>";

        echo "<td width=\"25%\"><font face=\"verdana2\">" . 
        $row["nombre"] . "</font></td>";

        echo "<td width=\"25%\"><font face=\"verdana3\">" . 
        $row["correo"] . "</font></td>";

        $numero++;
    }
    echo "<tr><td colspan=\"15\"><font face=\"verdana4\"><b>Número: " . $numero . 
    "</b></font></td></tr>";

    mysql_free_result($result);
    mysql_close($link);

    //comienzo a cambiar codigo postgresql por mysql 
?> 
</table>
    <div class="felote">
        <h2><font color="white"><?php echo ''.utf8_decode($row['nombre']); ?></h1></font>
    </div>
</div>
</div>
</div>
<!--PROBAR TABLA TERMINA AQUI-->
</body>
</html>

It does not do anything, I give it click and it does not carry out the ordering nevertheless the consultation if it does it. But for example I add a table for example this one:

<table id="myTable" class="tablesorter"> 
<thead> 
<tr> 
    <th>Last Name</th> 
    <th>First Name</th> 
    <th>Email</th> 
    <th>Due</th> 
    <th>Web Site</th> 
</tr> 
</thead> 
<tbody> 
<tr> 
    <td>Smith</td> 
    <td>John</td> 
    <td>[email protected]</td> 
    <td>$50.00</td> 
    <td>http://www.jsmith.com</td> 
</tr> 
<tr> 
    <td>Bach</td> 
    <td>Frank</td> 
    <td>[email protected]</td> 
    <td>$50.00</td> 
    <td>http://www.frank.com</td> 
</tr> 
</tbody> 
</table>

If it fulfills its function without any problem.

    
asked by Luis Alfredo Serrano Díaz 20.08.2017 в 22:37
source

1 answer

2

There are several things wrong with your code, for example mysql_ * this obsolete and should not be used instead you should use mysqli or PDO.

There are some dead, broken or poorly structured tags.

A version of your code could be the following:

<?php
    session_start();
    require 'funcs/conexion.php';
    include 'funcs/funcs.php';

    if(!isset($_SESSION["id_usuario"])){ //Si no ha iniciado sesión redirecciona a index.php
        header("Location: index.php");
    }
    $idUsuario = $_SESSION['id_usuario'];

    $sql = "SELECT id, nombre FROM usuarios WHERE id = '$idUsuario'";
    $result123 = $mysqli->query($sql);
    $row123 = $result123->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="css/paginaadministrar.css">
    <link href="css/bootstrap-3.3.7.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="css/paginaadministrar.css">
    <link rel="stylesheet" type="text/css" href="css/nuevabarra.css">
    <link href='https://fonts.googleapis.com/css?family=Oswald:400,700' rel='stylesheet' type='text/css'>

    <script type="text/javascript" src="/login/js/libs/jquery-1.6.1.min.js"></script> 
    <script type="text/javascript" src="/login/js/libs/jquery.tablesorter.js"></script>
    <script type="text/javascript" src="/login/js/libs/jquery.tablesorter.combined.js"></script>

    <script type="text/javascript">
        $(document).ready(function() 
        { 
            $("#myTable").tablesorter(); 
        });
    </script>
    <script type="text/javascript">
        $(document).ready(function() 
        { 
            $("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} ); 
        });
    </script>
    <style type="text/css">
        a:link   
        {   
         text-decoration:none;   
        }   
    </style>
</head>
<body>
<nav>
    <ul id="main">
        <li><a href='welcome.php' style='text-decoration:none;color:white;(otros)'>Inicio</a></li>
        <li>Eventos</li>
        <li><a href="perfil.php" style='text-decoration:none;color:white;(otros)'> Mi Perfil</a>
          <ul class="drop">
            <div>
            <li>Mis Reservaciones</li>
            <li>Mis Compras</li>
            <li><a href='logout.php' style='text-decoration:none;color:white;(otros)'>Cerrar Sesi&oacute;n</a></li>
            </div>
          </ul>
        </li>
        <li><a href='logout.php' style='text-decoration:none;color:white;(otros)'>Cerrar Sesi&oacute;n</a></li>
        <div id="marker"></div>
    </ul>
</nav>
<div align="center" class="main"> <!-- Primer Div Parallax -->
    <div align="center" class="container">
    <!-- Corrigo varios cierres de etiqueta -->
    <div class="felote">
        <h2>
            <font color="white"><?php echo ''.utf8_decode($row123['nombre']); ?></font>
        </h2>
    </div>
<!-- En esta area he creado un buscador para seleccionar el registro deseado -->   
<br><br/><br/><br/><br/>      
<table width="600" border="0" cellpadding="3" cellspacing="1" align="center">
    <tr>
    <!-- Corrigo varios cierres de etiqueta -->
        <td colspan=2><p><strong>Usuarios Registrados :</strong></p>
            <form method="POST" action="busqueda.php">
            <input type="TEXT" name="valor_a_buscar" size="30" style="border: 1px solid #7F9DB7;">
            <input type="submit" value="BUSCAR" name="enviar">
            <p>(Introduzca el nombre de usuario)</p>
            </form>
        </td>
    </tr>
</table>

<!-- tablesorter fin -->
<!--Probar tabla de aqui-->

<table id='myTable' class='tablesorter'>
<thead>
<tr>
    <td><font face="verdana1"><b>Usuario</b></font></td>
    <td><font face="verdana2"><b>Nombre</b></font></td>
    <td><font face="verdana3"><b>Correo</b></font></td>
    <td><font face="verdana3"><b>Contador</b></font></td>
</tr>
</thead>
<tbody>     
<!-- En este espacio probare consulta de tabla INICIA-->
<?php
    // por que hacer una nueva conexion cuando al principio haces una connexion 
    // ademas ¿por qué aqui utilizar mysql_*?
    /*
    $link = @mysql_connect("localhost", "root","")
      or die ("Error al conectar a la base de datos.");
        @mysql_select_db("login", $link)
      or die ("Error al conectar a la base de datos.");
    */
    /*if(!isset($_SESSION["id_usuario"])){ //Si no ha iniciado sesión redirecciona a index.php
        header("Location: index.php");
    }

    $idUsuario = $_SESSION['id_usuario'];*/
    //Consulta tabla usuarios

    $query = "SELECT usuario, nombre, correo FROM usuarios";
    // cambiamos esta linea utilizando la conexion del principio
    //$result = mysql_query($query);
    $result = $mysqli->query($query);

    $numero="0";
    //lo mismo aqui
    //while($row = mysql_fetch_array($result))
    while($row = $result->fetch_assoc())
    {
        echo "<tr><td width=\"25%\"><font face=\"verdana1\">" . 
        $row["usuario"] . "</font></td>";

        echo "<td width=\"25%\"><font face=\"verdana2\">" . 
        $row["nombre"] . "</font></td>";

        echo "<td width=\"25%\"><font face=\"verdana3\">" . 
        $row["correo"] . "</font></td>";

        echo "<td colspan=\"15\"><font face=\"verdana4\"><b>Número: " . $numero . 
        "</b></font></td></tr>";

        $numero++;

    }
    // esta linea esta mal deberia estar dentro del bucle y sobra un <tr>
    /*
        echo "<tr><td colspan=\"15\"><font face=\"verdana4\"><b>Número: " . $numero . 
        "</b></font></td></tr>";
    */

    //mysql_free_result($result);
    $result->free();

    //mysql_close($link);
    $mysqli->close();

    //comienzo a cambiar codigo postgresql por mysql 
?>
</tbody>
</table>

    <div class="felote">
        <h2><font color="white"><?php echo ''.utf8_decode($row['nombre']); ?></h2></font>
    </div>
</div>
</div>
</div>
<!--PROBAR TABLA TERMINA AQUI-->
</body>
</html>

I have commented on the code but to get you to the point:

  • line 70-75
  • line 78-89
  • line 101-154

That's what I've seen above.

Focusing on the part of the table that is what gives you problems, you must indicate the header and body of the table with thead and tbody , you could do something like this:

<table id='myTable' class='tablesorter'>
<!-- Añades thead -->
<thead>
    <tr>
        <!-- Cambiamos los td por th  en las celdas de la cabecera-->
        <th><font face="verdana1"><b>Usuario</b></font></th>
        <th><font face="verdana2"><b>Nombre</b></font></th>
        <th><font face="verdana3"><b>Correo</b></font></th>
        <!-- Cabecera para el contador -->
        <th><font face="verdana3"><b>Número</b></font></th>
    </tr>
</thead>
<!-- Añades tbody -->
<tbody>
<?php
    $query = "SELECT usuario, nombre, correo FROM usuarios";
    $result = $mysqli->query($query);
    // numero lo inicializamos en 1
    $numero=1;
    while($row = $result->fetch_assoc())
    {
        echo '<tr>';

        echo '<td width="25%"><font face="verdana1">'.$row["usuario"].'</font></td>';
        echo '<td width="25%"><font face="verdana2">'.$row["nombre"].'</font></td>';
        echo '<td width="25%"><font face="verdana3">'.$row["correo"].'</font></td>';
        // línea para el contador
        echo '<td width="25%"><font face="verdana3">'.$numero.'</font></td>';

        echo '</tr>';

        $numero++;

    }

?>
</tbody>
    
answered by 20.08.2017 / 23:35
source