Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Mostrar datos en tablas separadas

Estas en el tema de Mostrar datos en tablas separadas en el foro de PHP en Foros del Web. Buenas, tengo una duda. Tengo una TABLA que se llama ARTICULOS con las columnas: NOMBRE | DEPARTAMENTO | PRECIO Silla | 1 | 2 Mesa ...
  #1 (permalink)  
Antiguo 12/11/2013, 13:02
 
Fecha de Ingreso: octubre-2010
Mensajes: 45
Antigüedad: 13 años, 6 meses
Puntos: 0
Mostrar datos en tablas separadas

Buenas, tengo una duda. Tengo una TABLA que se llama ARTICULOS con las columnas:

NOMBRE | DEPARTAMENTO | PRECIO
Silla | 1 | 2
Mesa | 3 | 5
Televisor| 1 | 50

Código SQL:
Ver original
  1. SELECT * FROM ARTICULOS ORDER BY DEPARTAMENTO

E intento mostrar los articulos en varias tablas separadas por departamento

TABLA DEPARTAMENTO 1 -> Con los articulos que pertenezcan al departamento 1
TABLA DEPARTAMENTO 2 -> Con los articulos que pertenezcan al departamento 2
...
..
.

Se podría hacer algo así:
Código PHP:
while ($fila $consulta->fetch_assoc()) {
if (
$fila['DEPARTAMENTO'] == "1") { } 
Pero no hay alguna forma más correcta? No se si me explico bien..
  #2 (permalink)  
Antiguo 12/11/2013, 15:14
Avatar de quinqui  
Fecha de Ingreso: agosto-2004
Ubicación: Chile!
Mensajes: 776
Antigüedad: 19 años, 8 meses
Puntos: 56
Respuesta: Mostrar datos en tablas separadas

Holas, loCk636.

Con "tablas" supongo que te refieres a la presentación en la página web, no?

No debiera presentarte mucho problema si es eso, ya que tienes tu consulta de siempre, pero le agregas un ORDER BY departamento, para que luego en tu while, vayas abriendo y cerrando tabla HTML cada vez que el campo departamento cambie en el ciclo.

Saludos!
__________________
pipus.... vieeeeeji plomius!!!
*quinqui site*
  #3 (permalink)  
Antiguo 12/11/2013, 15:22
 
Fecha de Ingreso: octubre-2010
Mensajes: 45
Antigüedad: 13 años, 6 meses
Puntos: 0
Respuesta: Mostrar datos en tablas separadas

Cita:
Iniciado por quinqui Ver Mensaje
Holas, loCk636.

Con "tablas" supongo que te refieres a la presentación en la página web, no?

No debiera presentarte mucho problema si es eso, ya que tienes tu consulta de siempre, pero le agregas un ORDER BY departamento, para que luego en tu while, vayas abriendo y cerrando tabla HTML cada vez que el campo departamento cambie en el ciclo.

Saludos!
¿Como sería eso?
  #4 (permalink)  
Antiguo 12/11/2013, 15:27
Avatar de quinqui  
Fecha de Ingreso: agosto-2004
Ubicación: Chile!
Mensajes: 776
Antigüedad: 19 años, 8 meses
Puntos: 56
Respuesta: Mostrar datos en tablas separadas

Algo como esto (no te voy a hacer el código completo): le faltan muchas validaciones, pero la lógica general es la que te muestro:

Código PHP:
<?php
while ($fila $consulta->fetch_assoc())
{

 
// cada vez que encuentre que el departamento del registro es
 // distinto del anterior, muestra el inicio de tabla:
 
if ($ultimoDep != $fila['DEPARTAMENTO'])
 {
   
// aca imprimes el inicio de una nueva tabla HTML
   
?>
   <table>
   <?php // y el respectivo encabezado HTML, etc...
 
}

 
// aca solo imprimes tus articulos:
 
?>
  <tr><td><?php print $fila["ARTICULO"];  ?></td></tr>
 <?php

 
// siempre debes guardar el departamento para 
 // hacer la comparación en la siguiente vuelta del ciclo:
 
$ultimoDep $fila['DEPARTAMENTO'];

// fin del while

// y acá cierras la última tabla que quedó abierta
?>
</table>
Saludos!
__________________
pipus.... vieeeeeji plomius!!!
*quinqui site*
  #5 (permalink)  
Antiguo 12/11/2013, 15:52
 
Fecha de Ingreso: octubre-2010
Mensajes: 45
Antigüedad: 13 años, 6 meses
Puntos: 0
Respuesta: Mostrar datos en tablas separadas

Cita:
Iniciado por quinqui Ver Mensaje
Algo como esto (no te voy a hacer el código completo): le faltan muchas validaciones, pero la lógica general es la que te muestro:

Código PHP:
<?php
while ($fila $consulta->fetch_assoc())
{

 
// cada vez que encuentre que el departamento del registro es
 // distinto del anterior, muestra el inicio de tabla:
 
if ($ultimoDep != $fila['DEPARTAMENTO'])
 {
   
// aca imprimes el inicio de una nueva tabla HTML
   
?>
   <table>
   <?php // y el respectivo encabezado HTML, etc...
 
}

 
// aca solo imprimes tus articulos:
 
?>
  <tr><td><?php print $fila["ARTICULO"];  ?></td></tr>
 <?php

 
// siempre debes guardar el departamento para 
 // hacer la comparación en la siguiente vuelta del ciclo:
 
$ultimoDep $fila['DEPARTAMENTO'];

// fin del while

// y acá cierras la última tabla que quedó abierta
?>
</table>
Saludos!
Muchas gracias! Era lo que buscaba
  #6 (permalink)  
Antiguo 12/11/2013, 16:47
 
Fecha de Ingreso: enero-2011
Mensajes: 94
Antigüedad: 13 años, 3 meses
Puntos: 7
Respuesta: Mostrar datos en tablas separadas

Ese código me parece ineficiente lo mejor es mostrar la tabla normalmente y luego llamar a una funcion para que te muestre los artículos de ese departamento. No hay que validar nada.

bueno lo hice con Dreamweaver para ahorrar tiempo =)

Código CCS
Código CSS:
Ver original
  1. ul.tabla {
  2.     margin: 0px;
  3.     padding: 0px;
  4. }
  5.  
  6. ul.tabla ul {
  7.     margin: 0px;
  8.     padding: 0px;
  9. }
  10.  
  11. ul.tabla li {
  12.     height: 10px;
  13.     width: 200px;
  14.     padding-top: 5px;
  15.     padding-right: 0px;
  16.     padding-bottom: 15px;
  17.     padding-left: 0px;
  18.     border: 1px solid #C1C1C1;
  19.     float: left;
  20.     list-style-image: none;
  21.     list-style-type: none;
  22.     text-align: center;
  23.     margin-top: 0px;
  24.     margin-right: 0px;
  25.     margin-bottom: 5px;
  26.     margin-left: 0px;
  27. }
  28.  
  29. ul.tabla li.Top {
  30.     height: 20px;
  31.     width: 200px;
  32.     padding-top: 10px;
  33.     padding-right: 0px;
  34.     padding-bottom: 10px;
  35.     padding-left: 0px;
  36.     border: 1px solid #ABABAB;
  37.     float: left;
  38.     list-style-image: none;
  39.     list-style-type: none;
  40.     text-align: center;
  41.     background-color: #F5F5F5;
  42.     margin-top: 0px;
  43.     margin-right: 0px;
  44.     margin-bottom: 25px;
  45.     margin-left: 0px;
  46. }
  47.  
  48. ul.tabla li.Top2 {
  49.     height: 10px;
  50.     width: 140px;
  51.     padding-top: 10px;
  52.     padding-right: 0px;
  53.     padding-bottom: 10px;
  54.     padding-left: 0px;
  55.     border: 1px solid #ABABAB;
  56.     float: left;
  57.     list-style-image: none;
  58.     list-style-type: none;
  59.     text-align: center;
  60.     background-color: #F5F5F5;
  61.     margin-top: 0px;
  62.     margin-right: 0px;
  63.     margin-bottom: 10px;
  64.     margin-left: 0px;
  65. }
  66.  
  67. ul.tabla li.Articulos {
  68.     height: 20px;
  69.     width: 140px;
  70.     padding-top: 10px;
  71.     padding-right: 0px;
  72.     padding-bottom: 10px;
  73.     padding-left: 0px;
  74.     border: 1px solid #ABABAB;
  75.     float: left;
  76.     list-style-image: none;
  77.     list-style-type: none;
  78.     text-align: center;
  79.     background-color: #FEFEFE;
  80.     margin-top: 0px;
  81.     margin-right: 0px;
  82.     margin-bottom: 10px;
  83.     margin-left: 0px;
  84. }
  85.  
  86. ul.tabla a {
  87.     font-family: Verdana, Geneva, sans-serif;
  88.     font-size: 12px;
  89.     font-weight: bold;
  90.     text-transform: capitalize;
  91.     color: #000000;
  92.     text-decoration: none;
  93.     text-align: center;
  94. }
  95.  
  96. #contenedor {
  97.     padding: 0px;
  98.     height: auto;
  99.     width: 610px;
  100.     margin-top: 0px;
  101.     margin-right: auto;
  102.     margin-bottom: 0px;
  103.     margin-left: auto;
  104. }
  105.  
  106. #contenedor2 {
  107.     padding: 10px;
  108.     height: auto;
  109.     width: 580px;
  110.     float: left;
  111.     background-color: #FBFBFB;
  112.     border: 1px solid #C1C1C1;
  113. }
  114. .Espacio {
  115.     padding: 0px;
  116.     height: 1px;
  117.     width: 600px;
  118.     background-color: #A7A7A7;
  119.     float: left;
  120.     margin-top: 25px;
  121.     margin-bottom: 25px;
  122.     border-top-width: 1px;
  123.     border-top-style: solid;
  124.     border-top-color: #979797;
  125. }

Código de la tabla
Código PHP:
Ver original
  1. if (!function_exists("GetSQLValueString")) {
  2. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  3. {
  4.   if (PHP_VERSION < 6) {
  5.     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  6.   }
  7.  
  8.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  9.  
  10.   switch ($theType) {
  11.     case "text":
  12.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  13.       break;    
  14.     case "long":
  15.     case "int":
  16.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  17.       break;
  18.     case "double":
  19.       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
  20.       break;
  21.     case "date":
  22.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  23.       break;
  24.     case "defined":
  25.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  26.       break;
  27.   }
  28.   return $theValue;
  29. }
  30. }
  31.  
  32. mysql_select_db($database_Prueba, $Prueba);
  33. $query_Departamentos = "SELECT * FROM departamento ORDER BY nombre ASC";
  34. $Departamentos = mysql_query($query_Departamentos, $Prueba) or die(mysql_error());
  35. $row_Departamentos = mysql_fetch_assoc($Departamentos);
  36. $totalRows_Departamentos = mysql_num_rows($Departamentos);


Código HTML

Código HTML:
Ver original
  1. <?php require_once('../Connections/Prueba.php'); ?>
  2. <?php include('articulos.php'); ?>
  3.  
  4. <div id="contenedor">
  5. <ul class="tabla">
  6.   <li class="Top"><a>departamento</a></li>
  7.   <li class="Top"><a>estado</a></li>
  8.   <li class="Top"><a>fecha creacion</a></li>
  9.   <?php do { ?>
  10.     <li><a><?php echo $row_Departamentos['nombre']; ?></a></li>
  11.     <li><a><?php echo $row_Departamentos['estado']; ?></a></li>
  12.     <li><a><?php echo $row_Departamentos['fecha_registro']; ?></a></li>
  13.     <li><a>articulos</a></li>
  14.     <?php echo articulos($row_Departamentos['id_departamento']); ?>
  15.     <div class="Espacio"></div>
  16. <?php } while ($row_Departamentos = mysql_fetch_assoc($Departamentos)); ?>
  17. </ul>
  18. </div>
  19.  
  20. <?php
  21. mysql_free_result($Departamentos);
  22. ?>


Código de la funcion
Código PHP:
Ver original
  1. if (!function_exists("GetSQLValueString")) {
  2. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  3. {
  4.   if (PHP_VERSION < 6) {
  5.     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  6.   }
  7.  
  8.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  9.  
  10.   switch ($theType) {
  11.     case "text":
  12.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  13.       break;    
  14.     case "long":
  15.     case "int":
  16.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  17.       break;
  18.     case "double":
  19.       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
  20.       break;
  21.     case "date":
  22.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  23.       break;
  24.     case "defined":
  25.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  26.       break;
  27.   }
  28.   return $theValue;
  29. }
  30. }
  31.  
  32. function articulos($colname_Articulos)
  33. {
  34.     global $database_Prueba, $Prueba;
  35. mysql_select_db($database_Prueba, $Prueba);
  36. $query_Articulos = sprintf("SELECT id_articulo, nombre, cantidad, precio, fecha_registro FROM articulo WHERE departamento = %s ORDER BY nombre ASC", GetSQLValueString($colname_Articulos, "int"));
  37. $Articulos = mysql_query($query_Articulos, $Prueba) or die(mysql_error());
  38. $row_Articulos = mysql_fetch_assoc($Articulos);
  39. $totalRows_Articulos = mysql_num_rows($Articulos);
  40. echo '<div id="contenedor2">';
  41.  
  42. echo '<ul class="tabla">';
  43. echo '<li class="Top2"><a>nombre</a></li>
  44.      <li class="Top2"><a>cantidad</a></li>
  45.       <li class="Top2"><a>precio</a></li>
  46.       <li class="Top2"><a>fecha</a></li>';
  47.   do {
  48.       echo '<li class="Articulos">'.$row_Articulos['nombre'].'</li>';
  49.       echo '<li class="Articulos">'.$row_Articulos['cantidad'].'</li>';
  50.       echo '<li class="Articulos">'.$row_Articulos['precio'].'</li>';
  51.       echo '<li class="Articulos">'.$row_Articulos['fecha_registro'].'</li>';
  52.     } while ($row_Articulos = mysql_fetch_assoc($Articulos));
  53. echo '</ul>';
  54. echo '</div>';
  55. mysql_free_result($Articulos);
  56. }


archivo conexión
Código PHP:
Ver original
  1. # FileName="Connection_php_mysql.htm"
  2. # Type="MYSQL"
  3. # HTTP="true"
  4. $hostname_Prueba = "localhost";
  5. $database_Prueba = "tu base de datos";
  6. $username_Prueba = "tu usuario";
  7. $password_Prueba = "tu clave";
  8. $Prueba = mysql_pconnect($hostname_Prueba, $username_Prueba, $password_Prueba) or trigger_error(mysql_error(),E_USER_ERROR);



como se ve
  #7 (permalink)  
Antiguo 13/11/2013, 08:14
Avatar de jonni09lo
Colaborador
 
Fecha de Ingreso: septiembre-2011
Ubicación: Estigia
Mensajes: 1.471
Antigüedad: 12 años, 7 meses
Puntos: 397
Respuesta: Mostrar datos en tablas separadas

Cita:
Iniciado por nedyer Ver Mensaje
Ese código me parece ineficiente lo mejor es mostrar la tabla normalmente y luego llamar a una funcion para que te muestre los artículos de ese departamento. No hay que validar nada.

bueno lo hice con Dreamweaver para ahorrar tiempo =)
Hablas de que un código ineficiente y cometes dos errores garrafales:

1. Usas mysql_* sabiendo (y si no lo sabes ahora lo sabes) de que está obsoleto
2. Usas dreamweaver siendo este un pésimo programa para trabaja con PHP, además de generarte código basura e innecesario. (aún si lo hiciste para ahorrar tiempo, eso no es excusa)

Antes de llamar algo ineficiente, por favor lo que hagas que no sea peor de lo que postean.

Saludos
__________________
Haz preguntas inteligentes-Como ser Hacker
No hacer preguntas por mensaje privado. No sólo no es inteligente sino que es egoísta.

Etiquetas: select, separadas, tabla, tablas
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 19:03.