What are the advantages of using JOIN in MySQL queries for PHP applications?

When working with relational databases in PHP applications, JOIN statements in MySQL queries are essential for combining data from multiple tables based on a related column. This allows us to retrieve information from different tables in a single query, reducing the number of queries needed and improving performance. JOINs also help in organizing and structuring data efficiently, making it easier to work with complex datasets.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Query using JOIN to retrieve data from multiple tables
$sql = "SELECT users.username, orders.order_id
        FROM users
        JOIN orders ON users.user_id = orders.user_id";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // Output data of each row
  while($row = $result->fetch_assoc()) {
    echo "Username: " . $row["username"]. " - Order ID: " . $row["order_id"]. "<br>";
  }
} else {
  echo "0 results";
}

$conn->close();
?>