Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Troubleshooting
Research
Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

Insert multiple records and values using checkbox

Avatar of krv123
krv123Flag for United States of America asked on
PHP
2 Comments1 Solution1792 ViewsLast Modified:
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
<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
Avatar of Roger Baklund
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answers