Is using a JOIN statement in MySQL queries a recommended approach for combining data into an array in PHP?

Using a JOIN statement in MySQL queries is a recommended approach for combining data into an array in PHP. By using JOIN, you can retrieve data from multiple tables in a single query, reducing the number of queries needed to fetch related data. This can improve performance and simplify your code by fetching all necessary data at once.

// Connect to MySQL 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 with JOIN statement to fetch data from multiple tables
$sql = "SELECT orders.order_id, customers.name, products.product_name
        FROM orders
        JOIN customers ON orders.customer_id = customers.customer_id
        JOIN products ON orders.product_id = products.product_id";
$result = $conn->query($sql);

// Fetch data into an array
$data = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// Close MySQL connection
$conn->close();

// Output data as JSON
echo json_encode($data);