Insert multiple values ​​into single mysql column?

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

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

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

ping for testing:

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

I thought that if I go through this request, I could hypothetically do this:

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

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

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

I really solved this using:

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

I hope this helps someone and thank you guys for your help!

+5
source share
3 answers

You can 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 will get:

INSERT INTO table (id, type) VALUES (1, 'type'), (2, 'type'), (3, 'type'), (4, 'type')
+6
source

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

id1, id2 |

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

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

id1 |
id2 |

id int,

0

If you have a series of checkboxes and want to insert values ​​into your table, you can skip them like this:

<?php

$values = array();

foreach ($_POST['field_name'] as $i => $value) {
    $values[] = sprintf('(%d)', $value);
}

$values = implode(',', $values);

$sql = "INSERT INTO `table_name` (`column_name`) VALUES $values";

This will give you an SQL query similar to:

INSERT INTO `table_name` (`column_name`) VALUES (1),(2),(3),(4)

I hope for this help.

0
source

All Articles