Skip to content
PHP Logo

How can one effectively query from multiple tables in PHP without repeating the query?

When querying from multiple tables in PHP, you can use JOIN clauses to combine the tables and retrieve the desired data in a single query. This helps avoid repeating the same query multiple times and improves the efficiency of your code.

php
<?php
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

// Query to retrieve data from multiple tables using JOIN
$query = "SELECT t1.column1, t2.column2
          FROM table1 t1
          JOIN table2 t2 ON t1.id = t2.id";

// Prepare and execute the query
$stmt = $pdo->prepare($query);
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results and do something with the data
foreach ($results as $row) {
    // Process the data
}
?>