Jump to content
Larry Ullman's Book Forums

Recommended Posts

I'm trying to build an online tool checkout application, so I'm working with script 10.5 to pull (tool names) from a database to populate a table.  I need to be able to select multiple tools (using checkboxes), and then submit that form to a shopping cart.
 
I've been able to add a checkbox to each result, but is this the correct way to give each checkbox the name associated with it?

// Fetch and print all the records....
$bg = '#eeeeee'; 
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');
echo '<tr bgcolor="' . $bg . '">
<td align="left">' . $row['category'] . '</td>
<td align="left">' . $row['name'] . '</td>
<td align="left"> <form action="view_cart.php" method="post">
<input type="checkbox" name="checked" value="$row['name']" /> </td>
';
} // End of WHILE loop.

And then to display the results?

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {

       echo "\t<tr>
		<td align=\"left\">{$row['name']}</td>
		</tr>\n";
	
	} // End of the WHILE loop.

It just feels like a shot in the dark, and so I wanted to ask.

Link to comment
Share on other sites

I'm not sure if I understand your code or what it is you're trying to do, but I'll have a go. The way your code is currently structured you're creating a form for every row in the database. I think maybe you want to try something like this

$bg = '#eeeeee'; 
echo ' <form action="view_cart.php" method="post"><table>';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
   $bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');
   echo '<tr bgcolor="' . $bg . '">
   <td align="left">' . $row['name'] . '</td>
   <td align="left">
   <input type="checkbox" name="checked[]" value="' . $row['name'] . '" id="' . $row['name'] . '"  /> </td></tr>';
}
?>
</table>
<input type="submit" name="submit" value="submit" />
</form>

The checkboxes are all set to a named array and each given a unique id so you can loop through them to see which ones have been checked when you process the form

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	echo 'you have added the following tools to your shopping cart:';
	foreach ($_POST['checked'] as $value) {
		echo " $value, ";
	}
}
Edited by margaux
  • Upvote 2
Link to comment
Share on other sites

 Share

×
×
  • Create New...