Receive variable value and insert multiple rows in MYSQL

0

I have the following variable:

$ids = "758,749";

The table has the columns: id, provider_id, accept.

When running a PHP script, I would like it to do something like this:

INSERT INTO tabela (id, id_prestador, aceite) VALUES (null, $iddecadaprestador1, '0');
INSERT INTO tabela (id, id_prestador, aceite) VALUES (null, $iddecadaprestador2, '0');

That is, the column provider_id is variable, each value being inside the $ ids variable and the other fields are fixed.

    
asked by anonymous 09.08.2017 / 18:22

1 answer

4

First you can use explode() to break between commas:

$array = explode(',', '758,749');

This will generate an array containing 758 and 749 , separated.

Then there are several ways to enter the values in the database. One of them is using Prepared-Statement, assuming you use MySQLi:

$stmt = $sql->prepare("INSERT INTO tabela (id_prestador, aceite) VALUES (?, '0')");

foreach($array as $idPrestador){
    $stmt->bind_param('i', $idPrestador);
    $stmt->execute();
}

$stmt->close();

If aceite has a default value of 0 you can omit it from the query. :)

    
09.08.2017 / 18:32