What is the common issue faced when trying to display multiple MySQL DB data side by side in PHP?
When trying to display multiple MySQL DB data side by side in PHP, a common issue is fetching the data from each database separately and then trying to align them in a single row. To solve this, you can fetch the data from each database into separate arrays and then loop through the arrays to display the data side by side.
<?php
// Connect to first database
$connection1 = new mysqli('localhost', 'username1', 'password1', 'database1');
// Fetch data from first database
$query1 = $connection1->query("SELECT * FROM table1");
$data1 = $query1->fetch_all(MYSQLI_ASSOC);
// Connect to second database
$connection2 = new mysqli('localhost', 'username2', 'password2', 'database2');
// Fetch data from second database
$query2 = $connection2->query("SELECT * FROM table2");
$data2 = $query2->fetch_all(MYSQLI_ASSOC);
// Display data side by side
echo "<table>";
echo "<tr><th>Data from Database 1</th><th>Data from Database 2</th></tr>";
for ($i = 0; $i < max(count($data1), count($data2)); $i++) {
echo "<tr><td>" . ($data1[$i]['column1'] ?? '') . "</td><td>" . ($data2[$i]['column1'] ?? '') . "</td></tr>";
}
echo "</table>";
?>