The code example from this page shows how to make a
MySQL SELECT with JOIN table of different database, using PDO.
The trick is to specify both the database name and table in the SQL query, by using the syntax:
database_name.table_name.
- This method works if you use an user and password for connecting to MySQL that has access to both databases.
Complete code example
// Data for connecting to MySQL
$mysql =['host'=>'localhost', 'dbname'=>'db_1', 'user'=>'root', 'pass'=>'password'];
//connects with PDO
try {
$conn = new PDO('mysql:host='. $mysql['host'] .'; dbname='. $mysql['dbname'], $mysql['user'], $mysql['pass']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //set the PDO error mode to exception
}
catch(PDOException $e){ exit('Connection failed: '. $e->getMessage());}
$sql ="SELECT t1.id, t1.name, t2.col_db2 FROM db_1.table1 AS t1
LEFT JOIN db_2.table2 AS t2 ON t1.id = t2.id";
$stmt = $conn->query($sql);
if($stmt !== false) {
//shows selected data
foreach($stmt as $row) {
echo $row['id'] .'--'. $row['name'] .'--'. $row['col_db2'] .'<br>';
}
}
else {
echo '0 results';
}
- In this way you can join multiple tables from different databases.
Daily Test with Code Example
HTML
CSS
JavaScript
PHP-MySQL
Which tag is used in <table> to create table header cell?
<thead> <th> <td><table><tr>
<th>Title 1</th>
<th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin.some_class {
line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()document.getElementById("id_button").onclick = function(){
window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()$ar_dir = scandir("dir_name");
var_export($ar_dir);