Foros del Web » Programando para Internet » PHP »

Paginator y sumas parciales

Estas en el tema de Paginator y sumas parciales en el foro de PHP en Foros del Web. Hola JPINEDO Es un poco largo pero si no pego el código no sé cómo explicarte el problema. Tengo esto que logré con ayuda de ...
  #1 (permalink)  
Antiguo 10/07/2005, 13:53
(Desactivado)
 
Fecha de Ingreso: septiembre-2004
Mensajes: 360
Antigüedad: 19 años, 7 meses
Puntos: 1
Paginator y sumas parciales

Hola JPINEDO

Es un poco largo pero si no pego el código no sé cómo explicarte el problema.
Tengo esto que logré con ayuda de Uds. y me falta adaptarlo para que funcione ok con tu Paginator. Lo que hago es ir sumando resultados parciales pero al paginarlos vuelve a '0' y arranca de nuevo... no sé cómo hacer para que arrastre el saldo anterior.
Código PHP:
//de aquí para arriba es la parte de variables de sesión y header.html que no vienen al caso
if(isset($_POST['from_date'])){
   $dia_in = $_POST['from_date'];
}else{
   $dia_in = $_GET['from_date'];
}
if(isset($_POST['to_date'])){
   $dia_fin = $_POST['to_date'];
}else{
   $dia_fin = $_GET['to_date'];
}
if(isset($_POST['from_month'])){
   $mes_in = $_POST['from_month'];
}else{
   $mes_in = $_GET['from_month'];
}
if(isset($_POST['to_month'])){
   $mes_fin = $_POST['to_month'];
}else{
   $mes_fin = $_GET['to_month'];
}
if(isset($_POST['from_year'])){
   $ano_in = $_POST['from_year'];
}else{
   $ano_in = $_GET['from_year'];
}
if(isset($_POST['to_year'])){
   $ano_fin = $_POST['to_year'];
}else{
   $ano_fin = $_GET['to_year'];
}
//hago mi consulta para saber cantidad de fees
$form_date1=$mes_in."/".$dia_in."/".$ano_in;
$form_date2=$mes_fin."/".$dia_fin."/".$ano_fin;
$convert1=mktime(0, 0, 0, $mes_in, $dia_in, $ano_in);
$convert2=mktime(23, 59, 59, $mes_fin, $dia_fin, $ano_fin);
$sqlalt="SELECT SUM(trans_fee) AS TOTAL_FEES, COUNT(trans_fee) AS NUMBER_FEES FROM transactions WHERE timestamp>=$convert1 AND timestamp<=$convert2 AND trans_fee>0 ORDER BY timestamp desc";
$resultalt = mysql_query($sqlalt, $con) or die("error en consulta <b>$con</b> :".mysql_error());
if ($row= mysql_fetch_array($resultalt))
{
$tot=$row['TOTAL_FEES'];
$num=$row['NUMBER_FEES'];
/* Liberar conjunto de resultados */
mysql_free_result($resultalt);

/* Cerrar la conexion */
mysql_close($con);
?>
<?php
//consulta para listar fees por fechas
include("config_alter.php");
if(isset(
$_POST['from_date'])){
   
$dia_in $_POST['from_date'];
}else{
   
$dia_in $_GET['from_date'];
}
if(isset(
$_POST['to_date'])){
   
$dia_fin $_POST['to_date'];
}else{
   
$dia_fin $_GET['to_date'];
}
if(isset(
$_POST['from_month'])){
   
$mes_in $_POST['from_month'];
}else{
   
$mes_in $_GET['from_month'];
}
if(isset(
$_POST['to_month'])){
   
$mes_fin $_POST['to_month'];
}else{
   
$mes_fin $_GET['to_month'];
}
if(isset(
$_POST['from_year'])){
   
$ano_in $_POST['from_year'];
}else{
   
$ano_in $_GET['from_year'];
}
if(isset(
$_POST['to_year'])){
   
$ano_fin $_POST['to_year'];
}else{
   
$ano_fin $_GET['to_year'];
}
$form_date1=$mes_in."/".$dia_in."/".$ano_in;
$form_date2=$mes_fin."/".$dia_fin."/".$ano_fin;
$convert1=mktime(000$mes_in$dia_in$ano_in);
$convert2=mktime(235959$mes_fin$dia_fin$ano_fin);

$_pagi_sql=("SELECT trans_fee AS FEE, timestamp AS DATETIME, status AS STATUS FROM transactions WHERE timestamp>=$convert1 AND timestamp<=$convert2 AND trans_fee>0 ORDER BY timestamp DESC ");
//Incluimos el script de paginación. Éste ya ejecuta la consulta
include("paginator.inc.php");
if (
$rowmysql_fetch_array($_pagi_result))
{
  
$fee=$row['FEE'];
  
$status=$row['STATUS'];
  
$i=0;
  
$buffer=0;
/* Impresion de resultados en HTML */
   
echo "<BR><br><center><strong>Commissions Details  $form_date1 - $form_date2<br><br></center></strong>";
   echo 
"<center><TABLE BORDER='1'>\n";
   echo 
"<TR BGCOLOR='e6e6e6'><TD><center><strong><small><small>DATETIME</small></small></center></TD><TD><center><strong><small><small>COMMISSION</small></small></center></TD><TD><center><strong><small><small>PARTIAL SUMS</small></small></center></strong></TD><TD><center><strong><small><small>STATUS</small></small></center></strong></TD></TR>";
DO
   {
     
$time =getdate($row['DATETIME']);
            
$time $time['mon']."/".$time['mday']."/".$time['year']."&nbsp;&nbsp;".$time['hours'].":".$time['minutes'].":".$time['seconds'];
            if(
$status=='1')
            {
                
$stat="Completed";
            }
            elseif(
$status=='0')
            {
                
$stat="Pending";
            }
  
$buffer+=$row['FEE'];
  
$subtotales["$i"]=$buffer;
  
$i++;
   echo 
"<TR><TD><small><small>".$time."</small></small></TD><TD align='right'><small><small>".$row["FEE"]."</small></small></TD><TD align='right'><small><small>".number_format($buffer,2,".",",")."</small></small></TD><TD align='right'><small><small>".$stat."</small></small></TD></TR>";
   }
   WHILE (
$row=mysql_fetch_array($_pagi_result));
   echo 
"\t</tr>\n";
   echo 
"</TABLE>";
   echo 
"<br><center><strong>Total Quantity: $num - Total Amount: $ $buffer</center></strong>";
echo 
"<br>";
 
//echo "Records on this page: ".mysql_num_rows($_pagi_result);
//Incluimos la barra de navegación
echo"<p>".$_pagi_navegacion."</p>";
echo
"<p>".$_pagi_info."</p>";
echo 
"<br><center><strong><a href='form_viewfees.php'>View Commissions by Date </a><br>";
echo 
"<center><strong><a href='viewallfees.php'>View All Commissions</a><br><br><br><br>";
}
else{
echo 
"<strong><big><center><br><br><br>No fees in this period</big></center></strong>";
echo 
"<center><strong><a href='form_viewfees.php'>Back </a><br><br><br><br>";
}
}
?>
No se rían mucho de mi codiguito
Alguna ayudita ?
  #2 (permalink)  
Antiguo 10/07/2005, 16:17
Avatar de jpinedo
Colaborador
 
Fecha de Ingreso: septiembre-2003
Ubicación: Lima, Perú
Mensajes: 3.120
Antigüedad: 20 años, 7 meses
Puntos: 41
Ufff... vaya problema.
De todas maneras se necesita otra consulta para calcular la suma acumulada en los registros anteriores a esta página.
Para esto podemos utilizar algunas variables devueltas por Paginator como $_pagi_actual, $_pagi_hasta, $_pagi_cuantos... Si hay otra manera más sencilla, por ahora no se me ocurre.
Código PHP:
// TODO LO ANTERIOR A ESTA LÍNEA PERMANECE IGUAL

//Incluimos el script de paginación. Éste ya ejecuta la consulta
include("paginator.inc.php");

// Vamos a calcular la variable $fee_acumulado.
//----------------------------------------------------------
if($_pagi_actual == 1){
    
// Si la página es la número 1, $fee_acumulado = 0.
    
$fee_acumulado 0;
}else{
    
// Si la página no es la primera, hay que sumar los "fee" de los registros anteriores, $fee_acumulado = 0.
    
$sql_suma "SELECT SUM(trans_fee) AS SUM_FEE 
                    FROM transactions 
                    WHERE timestamp >= $convert1 
                    AND timestamp<=$convert2 
                    AND trans_fee>0 
                    LIMIT 0, "
.($_pagi_hasta $_pagi_cuantos); // Se suman desde el primer registro hasta el últimio de la página anterior
    
$result_suma mysql_query($sql_suma) or die ("Error en la suma :: <b>$sql_suma</b> :: ".mysql_error());
    
$row_suma mysql_fetch_assoc($result_suma);
    
$fee_acumulado $row_suma['SUM_FEE'];
}
//---------------------------------------------------------

if ($rowmysql_fetch_array($_pagi_result)){
    
$fee $row['FEE'];
    
$status $row['STATUS'];
    
$i 0;
    
$buffer  $fee_acumulado// Aquí inicializamos el $buffer de manera distinta.
    
    /* Impresion de resultados en HTML */

// TODO LO POSTERIOR A ESTA LÍNEA PERMANECE IGUAL 
Pruébalo y nos cuentas.

Saludos
  #3 (permalink)  
Antiguo 10/07/2005, 23:23
(Desactivado)
 
Fecha de Ingreso: septiembre-2004
Mensajes: 360
Antigüedad: 19 años, 7 meses
Puntos: 1
Muchísimas gracias JPINEDO !
pero... algo estoy haciendo mal... es como si no le diera bola al LIMIT... porque en la primera página perfecto pero en la segundoa me arrastra el total general, es decir, en cada línea tengo el total general de toda la consulta más el registro que corresponde a esa línea.
Estoy intentando modificando aquí y allá pero nada
Cariños y mil gracias otra vez.
  #4 (permalink)  
Antiguo 11/07/2005, 00:26
Avatar de jpinedo
Colaborador
 
Fecha de Ingreso: septiembre-2003
Ubicación: Lima, Perú
Mensajes: 3.120
Antigüedad: 20 años, 7 meses
Puntos: 41
Vaya... tienes razón.
El LIMIT limita (valga la redundancia) el número de registros devuelto por la consulta, peor no limita los registros tomados por las funciones como SUM().

En este caso parece que lo que habrá que hacer es obtener el "id" del primer registro de cada página y repetir la consulta que te puse, sin el LIMIT y con un AND id<$primer_id.

En este caso no sé realmente si el id nos sirva, ya que estamos ordenando por timestamp. Voy a ponerte un ejemplo de cómo se haría con el timestamp. Pero si dos registros pudieran tener el mismo valor en este campo, elcódigo podría no funcionar correctamente.

Si el id de tus registros es entero auto-incremental y se corresponde en orden con el timestamp (o sea, si los orednas por id, también quedan ordenados por timestamp), mejor tomamos en lugar del timestamp, el id y se soluciona.
Código PHP:
// TODO LO ANTERIOR A ESTA LÍNEA PERMANECE IGUAL

$_pagi_sql "SELECT trans_fee AS FEE, 
                    timestamp AS DATETIME, 
                    status AS STATUS 
                FROM transactions 
                WHERE timestamp >= $convert1 
                    AND timestamp<=$convert2 
                    AND trans_fee>0 
                ORDER BY timestamp DESC"


//Incluimos el script de paginación. Éste ya ejecuta la consulta
include("paginator.inc.php");

// Leemos el timestamp del primer registro
$row_suma mysql_fetch_assoc($_pagi_result);
$timestamp_primer_registro $row_suma['DATETIME'];
// resetaemos el resultset
mysql_data_seek($_pagi_result0);


// Vamos a calcular la variable $fee_acumulado.
//----------------------------------------------------------
if($_pagi_actual == 1){
    
// Si la página es la número 1, $fee_acumulado = 0.
    
$fee_acumulado 0;
}else{
    
// Si la página no es la primera, hay que sumar los "fee" de los registros anteriores, $fee_acumulado = 0.
    
$sql_suma "SELECT SUM(trans_fee) AS SUM_FEE
                    FROM transactions
                    WHERE timestamp >= $convert1
                        AND timestamp <= $convert2
                        AND trans_fee > 0
                        AND timestamp > '$timestamp_primer_registro'"
// Se suman desde el primer registro hasta el últimio de la página anterior
    
$result_suma mysql_query($sql_suma) or die ("Error en la suma :: <b>$sql_suma</b> :: ".mysql_error());
    
$row_suma mysql_fetch_assoc($result_suma);
    
$fee_acumulado $row_suma['SUM_FEE'];
}
//---------------------------------------------------------

if ($rowmysql_fetch_array($_pagi_result)){
    
$fee $row['FEE'];
    
$status $row['STATUS'];
    
$i 0;
    
$buffer  $fee_acumulado// Aquí inicializamos el $buffer de manera distinta.
    
    /* Impresion de resultados en HTML */

// TODO LO POSTERIOR A ESTA LÍNEA PERMANECE IGUAL 
Saludos
  #5 (permalink)  
Antiguo 11/07/2005, 01:35
(Desactivado)
 
Fecha de Ingreso: septiembre-2004
Mensajes: 360
Antigüedad: 19 años, 7 meses
Puntos: 1


GRANDE JPINEDO !!! GRACIAS GRACIAS GRACIAS !!!

Lo hice con el 'id', puede suceder que haya 2 ó más 'timestamp' iguales y quedó 10 puntos.

Me impresiona tu sabiduría y tu generosidad
Muchos cariños y toda mi gratitud
  #6 (permalink)  
Antiguo 11/07/2005, 02:02
Avatar de jpinedo
Colaborador
 
Fecha de Ingreso: septiembre-2003
Ubicación: Lima, Perú
Mensajes: 3.120
Antigüedad: 20 años, 7 meses
Puntos: 41
Qué bueno que funcionó.

Y gracias por las gracias :) . Siempre son bien recibidas.

Saludos
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 07:51.