What is the purpose of using JOIN in PHP and how does it work?
When working with databases in PHP, JOIN is used to combine rows from two or more tables based on a related column between them. This allows you to retrieve data from multiple tables in a single query, making it more efficient and reducing the need for multiple queries.
// Example of using JOIN in PHP to retrieve data from two tables
$query = "SELECT users.name, orders.product
FROM users
JOIN orders ON users.id = orders.user_id";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "User: " . $row['name'] . " ordered: " . $row['product'] . "<br>";
}
} else {
echo "No results found";
}