Home > Article > Backend Development > How to Insert Multiple Checkbox and Textbox Arrays into a MySQL Database in PHP?
Inserting Multiple Checkbox Arrays
If checkbox values are not getting inserted into the database, there could be a discrepancy between the indexes of the name attribute in our HTML and the PHP array elements. To resolve this, we need to explicitly set unique indexes for each checkbox element:
<code class="html"><input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /> <input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /></code>
This will ensure that each checkbox has its own unique index in the $_POST['checkbox'] array.
Preventing Unchecked Checkboxes from Getting Inserted
To prevent unchecked checkboxes from being inserted into the database, we should explicitly check whether each checkbox was checked before inserting its value:
<code class="php">if(isset($_POST['checkbox'])) { foreach($_POST['checkbox'] as $check) { if(!empty($check)) { $check = implode(',', $_POST['checkbox']); $name = implode(',', $_POST['item']); $quantity = implode(',', $_POST['quantity']); } }</code>
Using the Prepared Statement Method for Insert Queries
Instead of using mysql_query, it's recommended to use prepared statements for insert queries to prevent SQL injection attacks. Here's how you can modify your insert method:
<code class="php">$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(); }</code>
Other Considerations
The above is the detailed content of How to Insert Multiple Checkbox and Textbox Arrays into a MySQL Database in PHP?. For more information, please follow other related articles on the PHP Chinese website!