0

What I wanna do is take the variable name $ingreso and increment it at the end to send a lot of variables with the same name but with a different number at the end,$ingreso1, ingreso2 etc, but I don't know how to concatenate it correctly. Please Help.

PHP Code:

 while ( $cont<= 15){           
      $sql = "INSERT INTO ingreso (vlr_ingreso, periodo_ingreso, proyecto_id_proyecto)
              VALUES ('$ingreso".$cont."','$cont','$proyecto_id');";
      $insert = mysqli_query($con, $sql);
    }

But it keeps returning $ingreso without the number at the end.

What I think its happening is that the $cont is being added at the end of the $ingreso content, not to the variable itself

Thanks for any help

Andrés Girón
  • 97
  • 1
  • 11

1 Answers1

1

You should be able to do it using the complex string syntax ({}).

while ( $cont<= 15){           
    $sql = "INSERT INTO ingreso (vlr_ingreso, periodo_ingreso, proyecto_id_proyecto)
          VALUES ('${'ingreso'.$cont}','$cont','$proyecto_id');";
    $insert = mysqli_query($con, $sql);
}

This way, the ${'ingreso'.$cont} will be parsed within the string to $ingreso1, $ingreso2, etc.

(Also, as AbraCadaver commented, you'll also need to increment $cont for this to work.)


This would be easier if you could make changes earlier in your code so that these were array keys rather than separate variables. For example, if you had an array like:

$ingreso[1] = 'something';
$ingreso[2] = 'something else';
$ingreso[3] = 'etc.';

Then you could use a foreach loop instead:

foreach ($ingreso as $periodo => $vlr) {
    $sql = "INSERT INTO ingreso (vlr_ingreso, periodo_ingreso, proyecto_id_proyecto)
            VALUES ('$vlr','$periodo','$proyecto_id');";
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80