Home >Database >Mysql Tutorial >How to Efficiently Insert Multiple Checkbox and Textbox Array Values into a MySQL Database Using PHP?
Inserting Array Data into MySQL Database
In PHP, inserting multiple checkbox and textbox array values into a MySQL database can be challenging. Here are some encountered problems and their solutions:
Checkbox Selection Misalignment
The issue with displaying all checkbox values, even unmarked ones, stems from incorrect array handling. To overcome this, index the checkbox names explicitly. For example:
<input type="checkbox" name="checkbox[0]" value="17" />
This ensures a direct correspondence between checkbox indexes and the corresponding item and quantity values.
Missing Database Insertion
Despite establishing a database connection, there seems to be a problem with actual data insertion. The incorrect use of MySQL functions is identified as the culprit.
MySQLi and MySQL APIs should not be intermixed. Instead of using mysql_query, use the appropriate $conn->query() method for database operations.
Code Example
$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(); }
Additional Considerations
The above is the detailed content of How to Efficiently Insert Multiple Checkbox and Textbox Array Values into a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!