Insert multiple records from php and mysql

0

I have the following code:

$cantidadcupos=$_POST['cantidad_cupos'];
$idparking=$_POST['idestacionamiento'];

for($i=0; $i<=count($cantidadcupos) ;$i++){

     $query="INSERT INTO  cupos(numero, estado, reserva_id_reserva, estacionamiento_id_estacionamiento) 
                    VALUES ('1','disponible','1','1111')";                   
}

try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
} catch (PDOException $ex) {

    $response["success"] = 0;
    $response["message"] = "Error base de datos2. Porfavor vuelve a intentarlo";
    die(json_encode($response));
}       

$response["success"] = 1;
$response["message"] = "El cupo se ha agregado correctamente";
echo json_encode($response);

The variable $cantidad_cupos receives a number, and according to that number I need to make the insertions in the bd, eg: cantidad_cupos=20 and make 20 records, but with the code that I have I can not do that, I think I'm missing a transformation of the variable or something like that, but I can not find the answer.

    
asked by Fernando Brito 29.06.2018 в 09:07
source

1 answer

0

By parts:

If $cantidadcupos is a number, your function count($cantidadcupos) is returning 1, possibly. This function is designed to count elements of an object with property Countable or% Array .

Then, the execute function $stmt->execute($query_params) does not take any argument if it is done as a call to objects, that is, you have plenty of $query_params (which I also do not see declared anywhere).

And finally, your query is being overwritten with each iteration of the loop ..., you're writing about query multiple times without executing it. You may want to know that you can do prepare once, and execute several times without having to re-prepare it.

In addition to not throwing an exception does not mean that it was successful, execute returns True or False depending on the success of the operation. That's what you should check.

    
answered by 29.06.2018 / 09:25
source