krv123
asked on
Insert multiple records and values using checkbox
Hello,
I have a form with that displays a text box that you enter a value in. Next to the text box is a checkbox. I am having trouble submitting data to the database and keeping each line matched together.
Thanks
I have a form with that displays a text box that you enter a value in. Next to the text box is a checkbox. I am having trouble submitting data to the database and keeping each line matched together.
Thanks
<form method="POST">
<table>
<?php
$query = "SELECT id,itemName,itemId FROM services";
$result = mysql_query($query) or die("Can't create query: " . mysql_error());
while ($row = mysql_fetch_array($result))
{
echo "
<tr>
<td>$row[itemName]</td>
<td><input type=\"hidden\" name=\"item[]\" value=\"$row[itemId]]\"><input type=\"text\" name=\"value[]\" ></td>
<td><input type='checkbox' name='checkbox[]' value='$row[id]'></td>
</tr>";
}
?>
</table>
<input type="submit" name="save" value="Save" />
</form>
<?php
if (isset($_POST['save']))
{
if ($_POST['checkbox'] == 0)
{
echo 'no items selected';
} else
{
// selected field values where checked
foreach ($_POST['checkbox'] as $id)
{
// grab $_POST info create vars
$userId = $_SESSION['userid'];
$itemId = $_POST['item'];
$itemValue = $_POST['value'];
/*
I have also used a for loop here to count the posted items so the vars would be $itemId[$i],$itemValue[$i]. Extracting as array from form.
They would not match up.
*/
// $queries is so that it enters multiple rows at once.
$queries = array();
$queries[] = "('$userId','$itemId','$itemValue')";
// $queries[] = "('$userId','$itemId[$id]','$itemValue[$id]')";
$piece = implode(", ", $queries);
$query = "INSERT INTO cust_services (user,item,value) VALUES $piece";
$result = mysql_query($query) or die(mysql_error());
}
}
}
?>
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER