PHP inserting multiple checkbox AND textbox arrays into MySQL Database

You shouldn’t be using implode. That puts a comma-separated list of everything in the form into each row that you insert, and repeats this for every box that’s checked. You should just insert one item in each row, by indexing the arrays.

However, when you have a checkbox in a form, it only submits the ones that are checked. The result of this is that the indexes of the $_POST['checkbox'] array won’t match up with the corresponding $_POST['item'] and $_POST['quantity'] elements. You need to put explicit indexes into the checkbox names so you can relate them.

<form method = "POST">

<input type = "hidden" name = "item[]" value = "cupcake">
<input type = "text" name = "items" value = "cupcake" readonly><br>
<b>Price :</b> <span name = "price" value = "3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>

<input type = "hidden" name = "item[]" value = "cake">
<input type = "text" name = "items" value = "cake" readonly><br>
<b>Price :</b> <span name = "price" value = "20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>

<input type = "submit" name = "insertBT"><br>
</form>

Then your PHP code can be like this:

$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $quantity, $price);
foreach ($_POST['checkbox'] as $i => $price) {
    $name = $_POST['name'][$i];
    $quantity = $_POST['quantity'][$i];
    $stmt->execute();
}

BTW, putting the prices in your HTML seems like a bad idea. Nothing stops the user from modifying HTML using the web inspector before they submit the form, so they could lower the price. You should get the prices from the database when processing the form.

Also, notice that in your original code you opened the database connection using MySQLi, but then you tried to do the insert using mysql_query instead of $conn->query(). You can’t mix APIs like that; myql_query can only be used when you open the connection with mysql_connect.

Leave a Comment