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 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 create a highlighted bolded text?
<q> <strong> <em>
<p>Address: <strong>http://CoursesWeb.net/</strong> - Tutorials.</p>
Which of these CSS codes displays the text bolded?
text-size: 18px; font-style: italic; font-weight: 800;
#id {
  font-weight: 800;
}
What JavaScript function can be used to call another function multiple times, to a specified time interval?
setInterval() setTimeout() push()
function someFunction() { alert("CoursesWeb.net"); }
setInterval("someFunction()", 2000);
Click on the correctly defined variable in PHP.
var vname = 8; $vname = 8; $vname == 8;
$vname = 8;
echo $vname;
Mysql SELECT JOIN tables on two different Databases

Last accessed pages

  1. PHP Unzipper - Extract Zip, Rar Archives (31751)
  2. html2canvas - Save page screenshoot on server (4877)
  3. Add, Change, and Remove Attributes with jQuery (46249)
  4. Change CSS file with jQuery (5371)
  5. Working with Symbols and their Instances (1713)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (306)
  2. Read Excel file data in PHP - PhpExcelReader (108)
  3. The Four Agreements (93)
  4. PHP Unzipper - Extract Zip, Rar Archives (90)
  5. The Mastery of Love (84)
Chat
Chat or leave a message for the other users
Full screenInchide