Error while traversing a for for an insertion

0

[

I present a problem when inserting this data, I insert in the table costs_quotes the amount of amounts that I say, for example amount of fees: 9, good according to that number that happens you must insert that number of times the data in the table cost_quotas, as seen in the image, plus every 3 fields I must do an increase of 20% of the previous amount. The problem is that as you see the first increase begins in the cost field3 and should start at cost4, and then if you do every 3 fields, but when you start doing it in the field3, the only thing I have thought is as if there was a field cost0, or have some error in how to raise the for. I have gone around it but I have not been able to find a solution, here is the function that makes the insertion and the increases] 1

function cuotas($cantidad,$monto)
{
$mysqli = new mysqli('localhost', 'root', '', 'pruebas');

$query = "INSERT INTO cuotas (cantidad) VALUES('$cantidad')";
$sql = $mysqli->query($query);

$val = mysqli_insert_id($mysqli);

$campos = "";
$valores = "";
$porcentaje = 0.2;
$aumenta = 3;

for($i = 1; $i <= $cantidad; $i++){
  if(($i>=1) && ($i % $aumenta)==0):
    $monto = $monto*(1+$porcentaje);
  endif;
  $campos .= 'costo' . $i . ' , ';
  $valores .= '' . $monto . ' , ';

}

if($campos != ''):
  $campos = substr($campos, 0, -2);
  $valores = substr($valores, 0, -2);
endif;

$query2 = "INSERT INTO 
costo_cuotas(id_cantidad,$campos)VALUES($val,$valores)";
$sql2 = $mysqli->query($query2);
    
asked by 12.08.2017 в 20:24
source

1 answer

0

Look at the part of the FOR

cycle
  

start it from 0

You execute and it works as you need it, I detail the code that I ran in console commenting some lines.

function cuotas($cantidad,$monto)
{

  $query = "INSERT INTO cuotas (cantidad) VALUES('$cantidad')";
  // $sql = $mysqli->query($query);
  // $val = mysqli_insert_id($mysqli);

  $campos = "";
  $valores = "";
  $porcentaje = 0.2;
  $aumenta = 3;

  for($i = 0; $i < $cantidad; $i++){
    if(($i>=1) && ($i % $aumenta)==0):
      $monto = $monto*(1+$porcentaje);
    endif;

    $datoTemporal = $i + 1;
    $campos .= 'costo' . $datoTemporal . ' , ';

    $valores .= '' . $monto . ' , ';

  }

  if($campos != ''):
    $campos = substr($campos, 0, -2);
    $valores = substr($valores, 0, -2);
  endif;

  echo $query2 = "INSERT INTO costo_cuotas(id_cantidad,$campos) VALUES ('3',$valores)";
  //$sql2 = $mysqli->query($query2);
}

cuotas('9','20000');
    
answered by 12.08.2017 / 20:58
source