Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to insert the selected values of checkboxes into a mysql database using php. I just can't understand why it's not working because it echoes out all the values fine, but it will only insert the first selected one into the database.

HTML:

<b>Injury type:</b>
Bruise <input type='checkbox' name='InjuryType[]' value='1'><br>
Cut <input type='checkbox' name='InjuryType[]' value='2'><br>
Graze <input type='checkbox' name='InjuryType[]' value='3'><br>
Break <input type='checkbox' name='InjuryType[]' value='4'><br>
Bump <input type='checkbox' name='InjuryType[]' value='5'><br>

PHP:

foreach($_POST['InjuryType'] as $value) {
$insert = mysql_query("INSERT INTO AccidentInjuryLink(InjuryID) VALUES ('$value')");
echo $value; 
}
share|improve this question
print_r($_POST); is the data what you expected? – Dagon Feb 21 at 20:00
1. Don't use the mysql driver, use PDO instead. This prevents SQL injections; I can also see that you're not escaping your posted values. 2. Maybe that column has a primary index which means all numbers must be unique, thus only inserting the first value. – silkfire Feb 21 at 20:01
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. (Also, like silkfire said, you're vulnerable to SQL injection here, too.) – Eric Feb 21 at 20:02
1  
Your code is open to SQL injection attacks, here is a brief overview of what they are and how to prevent them. – Dan Simon Feb 21 at 20:02
2  
stop 'spamming' the stop using mysql_* – Dagon Feb 21 at 20:07
show 4 more comments

1 Answer

up vote 1 down vote accepted

Maybe that column has a primary index which means all numbers must be unique, thus only inserting the first value.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.