8

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!

2
  • i think id dataType is int. Commented Sep 14, 2012 at 19:13
  • I just added an int cast and it only inserts a row for the first value Commented Sep 14, 2012 at 19:16

3 Answers 3

7

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')
Sign up to request clarification or add additional context in comments.

1 Comment

i was able to solve it without using implode, but thank you for the help!
0

Both query are completely different

insert into table('id1,id2','type') will insert single row

id1,id2 | type

whereas

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

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

will insert two rows

id1 | type
id2 | type

so if your id column is int type then you cant run first query

Comments

0

If you have a series of checkboxes, and wanting to insert the values into your table, you could loop through 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 a SQL query similar to:

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

Hope this help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.