Reputation:
i want to select two databases in php but when i code it gives error how i select two databases here is my code which i already tried:
<?php
@session_start ();
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "domain102,main102";
$mysqli = new mysqli ($dbhost, $dbusername, $dbpassword, $dbname);
if ($mysqli->connect_errno)
{
echo ("Failed to connect to MySQL: " . $mysqli->connect_error);
}
$GLOBALS ['mysqli'] = $mysqli;
?>
here is error
Warning: mysqli::mysqli(): (HY000/1049): Unknown database 'domain102,main102'
Upvotes: 1
Views: 615
Reputation: 4110
Use mysqli::select_db to switch databases on the same server:
$link = new mysqli($dbhost, $dbusername, $dbpassword, $dbname);
then
$link->select_db($dbname2);
Upvotes: 0
Reputation: 522081
"Selecting a database" simply means you set a default for which database in a server you're querying. If you didn't do that, you'd have to prefix all tables in your queries:
SELECT * FROM database1.table1
I guess that is what you're really trying to do here. You cannot "select two databases" at once because that doesn't make sense by the definition of what "selecting a database" means, but you can query other databases you haven't selected by simply prefixing the tables with the database name in your queries.
You can also switch to a different database on the server you're connected to at any time with mysqli::select_db
.
Upvotes: 3
Reputation: 20286
You can connect to one database server and create queries as @deceze suggested.
Moreover you can use query with USE
keyword to switch between databases
USE db1;
SELECT COUNT(*) FROM mytable; # selects from db1.mytable
USE db2;
SELECT COUNT(*) FROM mytable; # selects from db2.mytable
http://dev.mysql.com/doc/refman/5.0/en/use.html
Upvotes: 1
Reputation: 2708
If you want to use two databases then Just use following code:
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "domain102";
$mysqli = new mysqli ($dbhost, $dbusername, $dbpassword, $dbname);
$dbname = "main102";
$mysqli1 = new mysqli ($dbhost, $dbusername, $dbpassword, $dbname);
Upvotes: -2
Reputation: 28763
Try like
$dbname1 = "domain102";
$dbname2 = "main102";
$mysqli1 = new mysqli ($dbhost, $dbusername, $dbpassword, $dbname1);
if ($mysqli1->connect_errno)
{
echo ("Failed to connect to MySQL: " . $mysqli1->connect_error);
}
$mysqli2 = new mysqli ($dbhost, $dbusername, $dbpassword, $dbname2);
if ($mysqli2->connect_errno)
{
echo ("Failed to connect to MySQL: " . $mysqli2->connect_error);
}
You cont connect two databases with same instance
or even we can say in single instance
.
Upvotes: 8