How can PHP scripts be optimized to handle 1:n relationships between tables more effectively?
To optimize PHP scripts for handling 1:n relationships between tables more effectively, one approach is to use SQL JOIN statements to retrieve related data in a single query instead of making multiple queries. This reduces the number of database calls and improves performance. Additionally, using indexes on the columns involved in the relationship can speed up the retrieval process.
// Example code snippet using SQL JOIN to retrieve data from related tables
$query = "SELECT orders.order_id, orders.order_date, customers.customer_name
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Order ID: " . $row['order_id'] . "<br>";
echo "Order Date: " . $row['order_date'] . "<br>";
echo "Customer Name: " . $row['customer_name'] . "<br><br>";
}
} else {
echo "No orders found.";
}