SQL - Insert multiple row values ​​into a single column

I need help with the method of inserting values ​​into one column in different rows.

Right now I have a blasted array that gives me a value like this:

('12', '13', '14')

These numbers are the new identifiers that I want to insert into the database.
The code I used to crack the array is this:

$ combi = "('' .implode (" ',' ", $ box)." ') "; // Where $ box is the starting array

The query I'm planning on using is stuck here:

mysql_query (" INSERT INTO studentcoursedetails ( studentID) VALUES

One option is to repeat this, but I cannot, because the array will be circular; maybe 3 identifiers, maybe 20.
The loop does not seem to be correct. Any help would be appreciated.

+5
source share
6 answers

To insert multiple values ​​into a table, you must use the syntax (value1), (value2):

$combi = "('".implode("'), ('",$box)."')";

PS: this function is called row value constructors and is available with SQL-92

+3
source

Can you do something like this:

for($x = 0; $x < count($box); $x++)
{
  mysql_query("INSERT INTO studentcoursedetails (studentID) VALUES ($box[$x]);
}

This will work directly on your array, insert a new row for each value in the $ box field and also prevent the need to blow the array into comma-separated strings

- , .

+2

sql :

insert into studentcoursedetails (studentid) values
   (1),
   (2),
   (3),
+2

MySQL, :

sql> insert into studentcoursedetails (studentID)
   > values (('12'), ('13'), ('14'));

, PHP, .

+2

implode. VALUES; SELECT

$combi = " ".implode(" UNION ALL SELECT ",$box)." "; // Where $box is the initial array
mysql_query("INSERT INTO studentcoursedetails (studentID) SELECT " . $combi)

SELECT .. union dbms.

- , .

+1

, mysql_query, .

0

All Articles