Ver Mensaje Individual
  #5 (permalink)  
Antiguo 23/08/2011, 09:49
Avatar de andresdzphp
andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Sumar valores de varias cajas de texto

Bueno te dejaré un par de ejemplos:

Ejemplo # 1, con la primera forma que te dejé:

formulario.php

Código PHP:
Ver original
  1. <form action="sumar.php" method="post">
  2. <?php
  3.  
  4. for ($i=1; $i<=10; $i++) {
  5.     echo 'Valor '.$i.': <input type="text" name="cantidad[]" /><br />';
  6. }
  7. ?>
  8. <br /><input type="submit" value="Sumar cantidades" />
  9. </form>

sumar.php

Código PHP:
Ver original
  1. <?php
  2.  
  3. $total = 0;
  4.  
  5. if (isset($_POST['cantidad']) && !empty($_POST['cantidad'])) {
  6.     if (is_array($_POST['cantidad'])) {
  7.         $total = array_sum($_POST['cantidad']);
  8.     }
  9. }
  10.  
  11. echo $total;

Ejemplo # 2, una parecida a lo que estas haciendo:

formulario.php

Código PHP:
Ver original
  1. <form action="sumar.php" method="post">
  2. <?php
  3. $x=1;
  4. while ($x<=10) {
  5. echo 'Valor '.$x.': <input type="text" name="cantidad_'.$x.'" /><br />';
  6. $x++;
  7. }
  8. ?><br />
  9. <input type="hidden" name="campos" value="<?php echo $x; ?>" />
  10. <input type="submit" value="Sumar cantidades" />
  11. </form>

sumar.php

Código PHP:
Ver original
  1. <?php
  2.  
  3. $suma = 0;
  4.  
  5. if (isset($_POST['campos']) && !empty($_POST['campos'])) {
  6.     for ($i=1; $i<$_POST['campos']; $i++) {
  7.         if (isset($_POST['cantidad_'.$i]) && !empty($_POST['cantidad_'.$i])) {
  8.             $suma += $_POST['cantidad_'.$i];
  9.         }
  10.     }
  11. }
  12.  
  13. echo $suma;

Yo me quedaría con la primera. Con eso es suficiente para que hagas lo que necesitas.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP