Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple values in one column mysql?

Tags:

mysql

I have a table of checkboxes and values, if a user selects a checkbox they select the value of the id in an array called checkedHW for simplicity sake this is what code looks like:

$ids = implode(',',arrayofids);

$sql = "insert into table(id, type) values($ids,type);
$db->query($sql);

echo query for testing:

"insert into table('id1,id2','type')

I figured that if I loop through this query I could hypothetically do this:

"insert into table('id1','type');"

"insert into table('id2','type');"

but I'm not exactly quite sure how to do, any help would be wonderful :)

I actually solved it using:

for($i=0;$i<count(arrayofids); $i++){
$sql = "insert into table(id,type) values(array[$i], 'type'";
$db->query($sql);}

I hope that helps someone and thank you guys for the help!

like image 970
bubbles Avatar asked Sep 14 '12 19:09

bubbles


1 Answers

You could do something like this:

$base = 'INSERT INTO table (id, type) VALUES (';
$array = array(1, 2, 3, 4);
$values = implode(", 'type'), (", $array);
$query = $base . $values . ", 'type')";

$db->query($query);

This is what would be getting submitted:

INSERT INTO table (id, type) VALUES (1, 'type'), (2, 'type'), (3, 'type'), (4, 'type')
like image 185
Kermit Avatar answered Oct 13 '22 23:10

Kermit