I am trying to get multiple rows to insert into a mysql table from a form that allows for multiple checkboxes.
This is the form:
<input type='submit' name='invite-group' value='Invite To Group'>
<br />
<?php
$query2aac = mysql_query("SELECT * FROM follow WHERE yoozer1='$userdb1a' AND followaccept='Yes' ORDER BY yoozer2 DESC");
while($row2aac = mysql_fetch_array($query2aac))
{
$rowid = $row2aac['followid'];
$yoozer2aac = $row2aac['yoozer2'];
$yoozer2aacurl = strtolower($yoozer2aac);
$palurl = '<a href="http://www.bunchofus.com/fanpage/' . $yoozer2aacurl . '">' . $yoozer2aac . '</a>';
echo '<input type= "hidden" name = "id[]" value="' . $rowid . '"></input>';
echo '<input type= "checkbox" name = "friends[]" value="' . $yoozer2aac . '">' . $palurl . '</input><br />';
}
?>
This is the php:
if ($submit)
{
$submit = $_POST['invite-group'];
$date1 = date("Y-m-d");
$lowername = strtolower($username);
$combined = $_POST['friends'];
foreach ($combined as $username)
{
$insert1 = mysql_query("INSERT INTO grprequest VALUES ('','$grpid3','$username','$myuser','$grprights3','$grpactive3')");
}
}
?>
It is inserting one line into the database but not multiple lines. If I echo the username after the foreach, multiple usernames are showing.
If anyone could help I would appreciate it.
Based on the sample code you’ve provided, and the var_dump of
$combined, I’m not sure why it isn’t working for you. But perhaps you could try something like this:This will perform all of your inserts in one call to the database. I added an
echobefore performing the query so that you can see the exact query that’s being performed.One thing that you should definitely note is that it looks like your code is vulnerable to SQL injection. There are hundreds of places you can look to find out more about how to protect yourself, so just search for it. My favorite reference is Bobby Tables.
It also looks like your form is vulnerable to XSS attacks. You select data from the database and insert it directly into HTML, but you should sanitize it first (using something like
htmlspecialchars).