Php-mysql Course

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,, t2.col_db2 FROM db_1.table1 AS t1
 LEFT JOIN db_2.table2 AS t2 ON =";
$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

Which tag is used to add definition lists into a <dl> element?
<dt> <dd> <li>
  <dd> - Hyper Text Markup Language</dd>
  <dd> - Language for web pages</dd>
Which CSS property can hide an element on page, letting an empty space in its place?
display position visibility
#id {
  visibility: hidden;
Click on the event which is triggered when the mouse clicks on an object.
onclick onmouseover onfocus
document.getElementById("id").onclick = function(){
Indicate the PHP variable that contains the contents of both $_GET, $_POST, and $_COOKIE arrays.
if(isset($_REQUEST["id"])) {
  echo $_REQUEST["id"];
Mysql SELECT JOIN tables on two different Databases

Last accessed pages

  1. JavaScript Course - Free lessons (21055)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (107236)
  3. Understanding OOP - Object Oriented Programming (3737)
  4. Creating objects in ActionScript (8627)
  5. PHP PDO - Select query, fetch (23909)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (479)
  2. Register and show online users and visitors (337)
  3. JavaScript Course - Free lessons (249)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (248)
  5. querySelector and querySelectorAll (237)