Foros del Web » Programando para Internet » PHP »

Mostrar datos en tabla

Estas en el tema de Mostrar datos en tabla en el foro de PHP en Foros del Web. Buenas tengo un problemilla quiero mostrar los datos de una consulta sql en un tabla hecha en php o html es igual pero la tabla ...
  #1 (permalink)  
Antiguo 15/07/2018, 03:56
 
Fecha de Ingreso: febrero-2010
Mensajes: 2
Antigüedad: 14 años, 1 mes
Puntos: 0
Mostrar datos en tabla

Buenas tengo un problemilla quiero mostrar los datos de una consulta sql en un tabla hecha en php o html es igual pero la tabla tiene 17 filas y 5 columnas y quiero rellenar eso huecos con los datos de mi base de datos sin alterar la estructura de la tabla si es posible y como gracias.

Última edición por Dj_ToRk3; 15/07/2018 a las 04:04
  #2 (permalink)  
Antiguo 15/07/2018, 23:03
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Mostrar datos en tabla

Lo único que necesitas hacer es dibujar cada fila de la tabla HTML con sus cinco columnas respectivas apoyándote en el uso de dos estructuras cíclicas: una para las filas y otra para las columnas (como cuando se recorre la estructura de un arreglo bidimensional). En cada iteración, imprimirías los datos obtenidos en la consulta o algún mensaje (por ejemplo, una serie de guiones que indiquen que no hay dato alguno para mostrar) en la celda correspondiente a un dato nulo (que no se halla en la base de datos).

Código PHP:
Ver original
  1. <?php
  2. $conexion = mysqli_connect('server', 'user', 'password', 'database');
  3.  
  4.  
  5. $consulta = 'SELECT field1, field2, field3, field4, field5 FROM table';
  6. $resultados = mysqli_query($conexion, $consulta) or exit (mysqli_error($conexion));
  7.  
  8. if (mysqli_num_rows($resultados)){
  9.     //Arreglo que almacenará los datos obtenidos en la consulta
  10.     $datos = [];
  11.  
  12.     //Recorremos el conjunto de datos obtenidos en la consulta y los almacenamos en $datos
  13.     //De esta manera, podremos recorrerlo más adelante como a un arreglo bidimensional
  14.     while ($filas = mysqli_fetch_assoc($resultados)){
  15.         $datos[] = [
  16.             0 => $filas['field1'],
  17.             1 => $filas['field2'],
  18.             2 => $filas['field3'],
  19.             3 => $filas['field4'],
  20.             4 => $filas['field5']
  21.         ];
  22.     }
  23. ?>
  24.     <table>
  25.         <thead>
  26.             <tr>
  27.                 <th>Columna 1</th>
  28.                 <th>Columna 2</th>
  29.                 <th>Columna 3</th>
  30.                 <th>Columna 4</th>
  31.                 <th>Columna 5</th>
  32.             </tr>
  33.         </thead>
  34.         <tbody>
  35. <?php
  36.         //Bucle de las filas
  37.         for ($i = 0; $i < 17; $i++){
  38. ?>
  39.             <tr>
  40. <?php
  41.             //Bucle de las columnas
  42.             for ($j = 0; $j < 5; $j++){
  43. ?>
  44.                 <td>
  45. <?php
  46.                 //Si el dato existe y posee extensión
  47.                 if (isset($datos[$i][$j]) && strlen($datos[$i][$j])){
  48.                     echo $datos[$i][$j];
  49.                 }
  50.                 else{
  51.                     echo '---';
  52.                 }
  53. ?>
  54.                 </td>
  55. <?php
  56.             }
  57. ?>
  58.             </tr>
  59. <?php
  60.         }
  61. ?>
  62.         </tbody>
  63.     </table>
  64. <?php
  65. }
  66. ?>

__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand

Última edición por Alexis88; 15/07/2018 a las 23:12 Razón: Etiqueta de cierre
  #3 (permalink)  
Antiguo 16/07/2018, 12:58
 
Fecha de Ingreso: febrero-2010
Mensajes: 2
Antigüedad: 14 años, 1 mes
Puntos: 0
Respuesta: Mostrar datos en tabla

Código HTML:
Ver original
  1. <?php
  2. //Agregamos la conexión
  3. include ('conectar.php');
  4.  
  5. //Parametros de la plantilla
  6. date_default_timezone_set('Europe/Madrid');
  7. $ho = date("j/n/Y");
  8. $tecnico = "Abdelasis Hassan Hamed";
  9.  
  10. ////Obteniendo registros de la base de datos a traves de una consulta SQL
  11. $consulta = 'SELECT * FROM incidencias';
  12. $resultado = mysql_query($consulta) or die (mysql_error());
  13.  
  14. if (mysql_num_rows ($resultado)) {
  15.  
  16. $datos = [];
  17.  
  18. ?>
  19. <meta charset="UTF-8">
  20. <link rel="Stylesheet" href="css/stylesheet.css">
  21. <title>PARTES</title>
  22. <!--table
  23.     {mso-displayed-decimal-separator:"\,";
  24.     mso-displayed-thousand-separator:"\.";}
  25. @page
  26.     {margin:.75in .49in .75in .54in;
  27.     mso-header-margin:.3in;
  28.     mso-footer-margin:.3in;
  29.     mso-page-orientation:landscape;}
  30. -->
  31. </head>
  32. <body link="#0563C1" vlink="#954F72">
  33.  <?php
  34. while ($filas = mysql_fetch_assoc($resultado)){
  35.      $datos [] = [
  36.         0 => $filas['hora'],
  37.         1 => $filas['tiempo'],
  38.         2 => $filas['sistema'],
  39.         // 3 => $filas['vacio'],
  40.         4 => $filas['usuario'],
  41.         5 => $filas['area'],
  42.         6 => $filas['descripcion'],
  43.         7 => $filas['estado']
  44.     ];
  45.  }
  46.  ?>
  47. <table border=0 cellpadding=0 cellspacing=0 width=1062 style='border-collapse:
  48. collapse;table-layout:fixed;width:799pt' align="center">
  49.  <col width=66 style='mso-width-source:userset;mso-width-alt:2413;width:50pt'>
  50.  <col width=64 style='mso-width-source:userset;mso-width-alt:2340;width:48pt'>
  51.  <col width=82 style='mso-width-source:userset;mso-width-alt:2998;width:62pt'>
  52.  <col width=38 style='mso-width-source:userset;mso-width-alt:1389;width:29pt'>
  53.  <col width=138 style='mso-width-source:userset;mso-width-alt:5046;width:104pt'>
  54.  <col width=152 style='mso-width-source:userset;mso-width-alt:5558;width:114pt'>
  55.  <col width=445 style='mso-width-source:userset;mso-width-alt:16274;width:334pt'>
  56.  <col width=77 style='mso-width-source:userset;mso-width-alt:2816;width:58pt'>
  57.  <col width=80 style='mso-width-source:userset;mso-width-alt:2925;width:60pt'>
  58.  <tr height=25 style='height:18.75pt'>
  59.   <td height=25 class=xl65 width=66 style='height:18.75pt;width:50pt'>FECHA:</td>
  60.   <td colspan=2 class=xl78 width=146 style='border-right:.5pt solid black;
  61.  width:110pt'><?php echo "".$ho."" ?></td>
  62.   <td width=38 style='width:29pt'></td>
  63.   <td width=138 style='width:104pt'></td>
  64.   <td class=xl65 width=152 style='width:114pt'>TECNICO:</td>
  65.  <td colspan=2 class=xl74 width=511 style='border-right:.5pt solid black;
  66.  width:384pt'><?php echo "".$tecnico."" ?></td>
  67.   <td class=xl66 width=82 style='border-left:none;width:62pt'>Pag. Nº</td>
  68.  </tr>
  69.  <tr height=20 style='height:15.0pt'>
  70.   <td height=20 colspan=8 style='height:15.0pt;mso-ignore:colspan'></td>
  71.  </tr>
  72.  <tr height=23 style='height:17.25pt'>
  73.   <td height=23 class=xl68 style='height:17.25pt'>HORA</td>
  74.   <td class=xl68>TIEMPO</td>
  75.   <td class=xl68>SISTEMA</td>
  76.   <td class=xl68></td>
  77.   <td class=xl68>USUARIO</td>
  78.   <td class=xl68>AREA</td>
  79.   <td class=xl69>DESCRIPCIÓN</td>
  80.   <td class=xl68>ESTADO</td>
  81.   <td class=xl68>PARTE</td>
  82.  </tr>
  83.     <?php
  84.            //Bucle de las filas
  85.            for ($i = 0; $i < 17; $i++){
  86.    ?>
  87.                 <tr height=34 style='mso-height-source:userset;height:25.5pt'>
  88.     <?php
  89.                //Bucle de las columnas
  90.                for ($j = 0; $j < 9; $j++){
  91.    ?>
  92.                     <td height=34 class=xl70 style='height:25.5pt'>
  93.     <?php
  94.                    //Si el dato existe y posee extensión
  95.                    if (isset($datos[$i][$j]) && strlen($datos[$i][$j])){
  96.                        echo $datos[$i][$j];
  97.                    }
  98.                    else{
  99.                        echo '';
  100.                    }
  101.    ?>
  102.                     </td>
  103.     <?php
  104.                }
  105.    ?>
  106.                 </tr>
  107.     <?php
  108.            }
  109.    ?>
  110.         <?php
  111.    }
  112.    ?>
  113.  
  114.   <tr height=20 style='height:15.0pt'>
  115.   <td height=20 colspan=8 style='height:15.0pt;mso-ignore:colspan'></td>
  116.  </tr>
  117.  <tr height=20 style='height:15.0pt'>
  118.   <td colspan=6 height=20 class=xl77 style='height:15.0pt'><font class="font5">N.Usuario:</font><font
  119.  class="font0"> 0=Nada, 1=Tramita con dificultad; 2=Tramita Nivel Medio;
  120.   3=Controla</font></td>
  121.   <td colspan=2 style='mso-ignore:colspan'></td>
  122.  </tr>
  123.  <tr height=20 style='height:15.0pt'>
  124.   <td colspan=6 height=20 class=xl77 style='height:15.0pt'><font class="font5">Estado:</font><font
  125.  class="font0"> OK=Cerrado; TR=Traslado</font></td>
  126.   <td colspan=2 style='mso-ignore:colspan'></td>
  127.  </tr>
  128.  <tr height=0 style='display:none'>
  129.   <td width=66 style='width:50pt'></td>
  130.   <td width=64 style='width:48pt'></td>
  131.   <td width=82 style='width:62pt'></td>
  132.   <td width=38 style='width:29pt'></td>
  133.   <td width=138 style='width:104pt'></td>
  134.   <td width=152 style='width:114pt'></td>
  135.   <td width=445 style='width:334pt'></td>
  136.   <td width=77 style='width:58pt'></td>
  137.  </tr>
  138. </body>
  139. </html>

Funciono gracias ahora tengo un problema en una columna la cual la quiero justificar a la izquierda las otras que esten centradas que solucion me das gracias.

Última edición por Dj_ToRk3; 17/07/2018 a las 12:43
  #4 (permalink)  
Antiguo 18/07/2018, 06:26
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Mostrar datos en tabla

Eso puedes hacerlo con CSS. Al momento de imprimir cada celda, puedes asignar una clase X a las celdas cuyo contenido quieres alinear al centro y una clase Y a aquella cuyo contenido quieres alinear a la izquierda.

Por ejemplo, supongamos que la tercera celda tendrá el texto alineado a la izquierda y las demás al centro:

Código PHP:
Ver original
  1. <?php
  2.     //Bucle de las columnas
  3.         for ($j = 0; $j < 5; $j++){
  4.             if ($j == 2){ //Si es la tercera celda (se empieza a contar desde cero)
  5.                 $clase = 'left';
  6.             }
  7.             else{
  8.                 $clase = 'center';
  9.             }
  10. ?>
  11.             <td class="<?=$clase?>"> <!-- Aquí signas la clase a la celda -->
  12. <?php
  13.             //Si el dato existe y posee extensión
  14.             if (isset($datos[$i][$j]) && strlen($datos[$i][$j])){
  15.                 echo $datos[$i][$j];
  16.             }
  17.             else{
  18.                 echo '---';
  19.             }
  20. ?>
  21.             </td>
  22. <?php
  23.         }
  24. ?>

Luego, en tu hoja de estilos (CSS), solo necesitarás establecer a las clases y sus respectivas reglas:

Código CSS:
Ver original
  1. .left{
  2.     text-align: left;
  3. }
  4.  
  5. .center{
  6.     text-align: center;
  7. }

__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand

Etiquetas: html, sql, tabla
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 14:10.