Run Insert to table within loop with PDO

1

I send the year to my class and I want to insert records in the form AAAAMM ( integer ) The MM is of the form 01, 02 .... 11, 12. But it does not execute the class. Show error in the Insert .

public function InsertarMesesAnio($anio){
for ($i = 1; $i <= 12; $i++) {
    $mes = str_pad($i, 2, "0", STR_PAD_LEFT);
    $periodo = $anio.$mes;
    $sql = "INSERT INTO tperiodo (periodo, estado)
        VALUES :periodo, 'P'";
}
$BD = new ConexionDB();
$sth = $BD->prepare($sql);          
$sth->bindParam(':anio', $anio, PDO::PARAM_INT);
$sth->execute();
}
    
asked by Piropeator 21.07.2018 в 08:33
source

1 answer

1

You have already solved the function of generating the elements to insert, but you have specific errors

  • The parameter is named periodo in your sentence and in bind is anio , you will have to decide which one you stay with.
  • You have a syntax error to pass the VALUES() , it goes in parentheses.
  • I do not see the need to have a string that will never change in a for , if for could be used to insert the elements, after prepare the statement to only assign the generated values .
  • Possible Final Function

        public function InsertarMesesAnio($anio){
          $BD = new ConexionDB();  
          $sql = "INSERT INTO tperiodo (periodo, estado)
                VALUES (:periodo, 'P')";
          //Preparamos la sentencia una sola vez
          $sth = $BD->prepare($sql); 
          for ($i = 1; $i <= 12; $i++) {
              $mes = str_pad($i, 2, "0", STR_PAD_LEFT);
              $periodo = $anio.$mes;
              //Asignamos el valor generado al parámetro y ejecutamos la sentencia
              $sth->bindParam(':periodo', $periodo, PDO::PARAM_INT);
              $sth->execute();
          }
        }
    
        
    answered by 21.07.2018 / 08:54
    source