To fetch and display data from multiple database tables using PDO joins in PHP, you can follow these steps:
$dbHost = "your_host";
$dbName = "your_database";
$dbUser = "your_username";
$dbPass = "your_password";
try {
$db = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
die();
}
$query = "SELECT t1.column1, t1.column2, t2.column3 FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.id = t2.id";
In this example, 'table1' and 'table2' are the names of the tables you want to join. Replace 'column1', 'column2', and 'column3' with the specific column names you want to retrieve.
try {
$stmt = $db->prepare($query);
$stmt->execute();
} catch(PDOException $e) {
echo "Query failed: " . $e->getMessage();
die();
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['column1'] . " | " . $row['column2'] . " | " . $row['column3'] . "<br>";
}
This code assumes that 'column1', 'column2', and 'column3' are the column names you retrieved in the SQL query. Change them accordingly to match the actual column names.
By following these steps, you can retrieve and display data from multiple database tables using PDO joins in PHP. Adjust the SQL query, column names, and display logic to fit your specific requirements.