How to connect multiple MySQL databases on a single webpage ?
Last Updated :
15 Jul, 2021
This article explains how to connect multiple MySQL databases into a single webpage. It is useful to access data from multiple databases.
There are two methods to connect multiple MySQL databases into a single webpage which are:
- Using MySQLi (Improved version of MySQL)
- Using PDO (PHP Data Objects)
Syntax:
- MySQLi Procedural syntax:
$link = mysqli_connect( “host_name”, “user_name”, “password”, “database_name” );
- MySQLi Object Oriented syntax:
$link = new mysqli( “host_name”, “user_name”, “password”, “database_name” );
- PDO (PHP Data Objects) syntax:
$pdo = new PDO( “mysql:host=host_name; dbname=database_name”, “user_name”, “password” );
Program: This program uses MySQLi to connect multiple databases on a single webpage.
PHP
<?php
$link1 = mysqli_connect( "localhost" , "root" , "" , "database1" );
if ( $link1 == true) {
echo "database1 Connected Successfully" ;
}
else {
die ( "ERROR: Could not connect " . mysqli_connect_error());
}
echo "<br>" ;
$link2 = mysqli_connect( "localhost" , "root" , "" , "database2" );
if ( $link2 == true) {
echo "database2 Connected Successfully" ;
}
else {
die ( "ERROR: Could not connect " . mysqli_connect_error());
}
echo "<br><br>Display the list of all Databases:<br>" ;
$link = mysqli_connect( 'localhost' , 'root' , '' );
$res = mysqli_query( $link , "SHOW DATABASES" );
while ( $row = mysqli_fetch_assoc( $res ) ) {
echo $row [ 'Database' ] . "<br>" ;
}
?>
|
Output:
Share your thoughts in the comments
Please Login to comment...