What are the potential pitfalls of using while loops to fetch data from multiple SQL tables in PHP?
Using while loops to fetch data from multiple SQL tables in PHP can lead to performance issues, as it may result in multiple queries being executed sequentially. To optimize this process, you can use JOIN queries to fetch data from multiple tables in a single query, reducing the number of database calls and improving performance.
// Example of using JOIN query to fetch data from multiple tables
$query = "SELECT users.username, orders.order_id
FROM users
JOIN orders ON users.user_id = orders.user_id";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
// Process fetched data
echo $row['username'] . " - " . $row['order_id'] . "<br>";
}
}