PHP Insertion of Multiple Checkbox and Textbox Arrays into MySQL Database
Inserting multiple arrays of checkbox and textbox values into a MySQL database using PHP poses unique challenges. Let's address two common issues:
Incorrect Checkbox Display:
The provided HTML form doesn't explicitly index the checkbox names. As a result, all checkboxes are displayed as checked, regardless of their actual state.
Solution: Index the checkbox names using a unique identifier for each checkbox. For example:
<code class="html"><input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /> <input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /></code>
Data Insertion Failure:
Although the connection to the database is established, the data insertion into the purchases table is failing.
Solution:
<code class="php">foreach ($_POST['checkbox'] as $i => $price) { $name = $_POST['name'][$i]; $quantity = $_POST['quantity'][$i]; //... }</code>
<code class="php">$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)"); $stmt->bind_param("sis", $name, $quantity, $price); $stmt->execute();</code>
The above is the detailed content of How to Insert Multiple Checkbox and Textbox Arrays into a MySQL Database with PHP?. For more information, please follow other related articles on the PHP Chinese website!