Receive variable value and insert multiple rows into MYSQL

Asked

Viewed 678 times

0

I have the following variable:

$ids = "758,749";

Table has columns: id, id_provider, accepted.

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 id_provider column is variable, and each value is within the $ids variable and the other fields are fixed.

  • Fields separated by comma ? 758 would be a $iddecadaprestador1 and 749 the other $iddecadaprestador1?

  • If id is pk and auto increment, you don’t even need to use in your query, now in your specific problem... just give a $a = explode(",",$ids) and make a foreach($a as $id_prestador){ $Query = "seu insert".$id_prestador; } echo $Query;

  • isos, each number would be an id

  • thanks @Marceloboni worked right!

1 answer

4


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

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

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

Then there are several ways to enter the values into the database. One of them is by 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 the aceite has a default value of 0 you can omit it from query. :)

  • appeared the following msg: Fatal error: Uncaught Error: Cannot pass Parameter 3 by Reference on line $stmt->bind_param('si', $idPrestador, 0);

  • Not again Warning: mysqli_stmt::bind_param(): invalid Object or Resource mysqli_stmt in. to make the connection right? $link = mysqli_connect("localhost", "user", "password", "bank");

  • $stmt->bind_param('i', $idPrestador);

  • @13dev, exact, altered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.