What are the best practices for structuring HTML forms and PHP code to efficiently handle and save multiple data rows in a database?
When handling multiple data rows in HTML forms and PHP, it is best to use arrays for input field names to easily loop through and process the data. This allows for efficient handling and saving of multiple rows of data in a database. By dynamically generating input field names with array syntax in the HTML form and processing them in PHP using loops, you can easily handle and save multiple rows of data without repetitive code.
// HTML form with array syntax for input field names
<form method="post" action="process.php">
<input type="text" name="item[]" />
<input type="text" name="quantity[]" />
<input type="text" name="price[]" />
<input type="text" name="item[]" />
<input type="text" name="quantity[]" />
<input type="text" name="price[]" />
<!-- Add more rows as needed -->
<input type="submit" value="Submit" />
</form>
// PHP code in process.php to handle and save multiple rows of data
<?php
// Connect to database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Loop through the array of input fields
for ($i = 0; $i < count($_POST['item']); $i++) {
$item = $_POST['item'][$i];
$quantity = $_POST['quantity'][$i];
$price = $_POST['price'][$i];
// Insert data into database
$stmt = $pdo->prepare("INSERT INTO items (item, quantity, price) VALUES (?, ?, ?)");
$stmt->execute([$item, $quantity, $price]);
}
echo "Data saved successfully";
?>