How to include two database connections? - php

I have included 1 database connection in my PHP file. The file that connects to the database is called connect.php. This works successfully with no errors. When I try to include 2 database connections in my PHP file, this is when I encounter errors. It seems as though, I can only connect to one database at a time because only 1 of the databases are connected. Is there a way to include 2 database connections in 1 file?
This is what I have right now:
<?php
require "connect.php";
require "informational-connect.php";
?>
This is what's included in connect.php:
<?php
$db= new mysqli("localhost", "XXX", "XXX", "ARTICLES");
if($db->connect_errno)
{
die("Error");
}
?>
This is what's included in informational-connect.php:
<?php
$db = new mysqli("localhost", "XXX", "XXX", "INFORMATION-DATA");
if ($db->connect_errno)
{
echo die("Error");
}
?>
I am using MySQLi.

In order to have different connections you have to give the connection variables different names
Besides, you need only one database to deal with, and therefore only single connection

The database selection is associated with the connection resource. So you can select it once for each connection.
If you don't call mysql_select_db at all,then all your queries will need to specify explicit database prefixes before all the tables, e.g. select * from db1.table ....

mysqli is provide a functionality for connect multiple database at a time.
But How one single variable in a file can hold two different
connections ?
You should use two different variables for each database connection.
$Db1 = new mysqli($hostname,$username,$password,$db_name1); // connection 1
$Db2 = new mysqli($hostname,$username,$password,$db_name2); // connection 2

Related

PHP Prevent multiple MySQL Connections

I have a large procedural style php/mysql website, which is splitted into many different files. Within each file, i include my dbconn.php, to ensure, that a db connection is available.
It looks something likes this:
index.php
<?php
include_once ('header.php');
include_once ('nav.php');
include_once ('content.php');
include_once ('sidebar.php');
include_once ('footer.php');
?>
and within each of these files i call several other files via include_once. So in total i come up with about 30 different files.
Every file starts with:
include_once($_SERVER['DOCUMENT_ROOT'].'/dbconn.php');
Since i'm using include_once, dbconn.php should not be loaded more then once, but recently i get following php warning.
PHP Warning: mysqli_connect(): (HY000/1226): User 'username' has exceeded the 'max_user_connections' resource (current value: 20) in /var/www/html/dbconn.php on line 10
My dbconn.php looks like this:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$db = "dbname";
if(!mysqli_thread_id($con)){
$con = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($con, 'utf8');
}
unset($host,$user,$pass,$db);
?>
So there is a double check.
If there already is an open mysql connection, the file should do basicly nothing.
What am i doing wrong?
Why do i get this php warning and how do i reduce the amount of mysql connections?
Basically, it's not different calls from a single page that is leading to the problem. It's the fact that you have multiple OPEN connections at the moment.
Make sure you close you connections after they have served their purpose.
Also, try to avoid the kind of structure you currently have, have all the DB related stuff included in one file and then include it only once on your page.
I solved the problem by using a singleton pattern.
So i changed the mysqli prodecural code into mysqli objectoriented.
i got the pattern here:
http://www.davecomeau.net/blog/1/Single+Database+Object+in+PHP+5+Using+the+Singleton+Pattern

connecting to multiple databases on different servers in php

I am trying to connect to two different databses using php
error_reporting(E_ALL);
$con= mysqli_connect("localhost", "phpapp", "phpapp", "hazard") or die("error connecting database 1".mysqli_error($con));
$con_vpn= mysqli_connect("xxx.xxx.xxx.xxx", "user", "pass", "db_name") or die("error connecting database 2".mysqli_error($con_vpn));
When I run the application it is showing error : error connecting database 2. It is not even printing the error.
thanks in advance:)
That's because you're trying to use a handle from a failed connection. Since the connection failed, that handle is invalid. That's why there mysqli_connect_error(), which will return the error message from the LAST attempted connection.
$con_vpn = mysqli_connect(....) or die(mysqli_connect_error());
Note that the connect_error function takes no parameters - it doesn't need any.

Connecting to a mysql database without keeping details in the script

I am attempting to create a separate login file for database connections as I am not too fond of having all the access details on each page that requires database access.
I have created a separate file on my server that contains the variables required for a successful login and then use the;
include_once('path_to_file/filename.php');
to get the variables and then use;
$dbconnection = mysqli_connect("$hostname","$username","$password","$database") or die ("Could not connect to the server");
but the connection fails every time. I tried including the connection script in the file I am attempting to include but then I get this message:
Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2)
I'm not really sure how to fix this, but every page in my server more or less access the database and I think it has to be a security risk having login details replicated everywhere!
Anyone have any suggestions or alternatives?
databaseloging format is:
<?php
# parameters for connection to MySQL database
$hostname="hostname";
$database="databasename";
$username="username";
$password="password";
?>
P.S. I have also tried require and got the same result.
Also when using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
http://www.php.net/manual/en/function.mysql-connect.php

Fetching data from multiple databases with MySQLi

i'am using MySQLi to connect and fetch data from my MySQL server with
$link = new mysqli("localhost", "root", "","database_1");
I have a file that used for connection and data collection (dboperations.php) from above database
Now , i need to connect another database (e.g. database_2) and fetch data in the same php file.
Conditions:
Are databases on the same server? YES
Am i authorized to connect with same username and pass? YES
Is there any way to do that? Thanks.
Use mysqli::select_db to switch databases on the same server:
$link = new mysqli('localhost', 'root', '', 'database1');
then
$link->select_db('database2');
SELECT * FROM database_2.table ...

PHP connecting to DB : OOP vs Procedural 1 dont work 2 works

I am scratching my empty head with this issue:
When I have my logging data as procedural, everything works fine. I require the file once and can proceed with my select queries. If the connection to the DB file is however written as OOP. I get the error that No database selected
====
<?php
// SETTING VALUES AS CONSTANTS
DEFINE('DB_USER', 'root');
DEFINE('DB_PASSWORD', '');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'tra');
// CONNECTING JUST TO THE SERVER
$dbc = #mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$dbc) // IF IT CAN'T CONNECT, ISSUE A MESSAGE
{
die('Could not connect: ' . mysql_error());
}
// CONNECTING NOW TO THE DB
mysql_select_db("tra", $dbc);
?>
So that up there works fine. I have got that in a separate file, (out of the root path)
But if I try to do it OOP, then, the rest of the queries that are to work once I have the access to the DB won't work. I sometimes get the query written as output, I mean as if not executing, just the plain text:
$mysqli = new mysqli("localhost", "root", "");
$mysqli->select_db("tra");
I have tried tons of varieties with the OOP version, first instantiating separately such as
$mysqli = new mysli();
$mysqli->connect("127.0.0.1", "root", "", "tra");
or also
$mysqli = new mysqli("localhost", "root", "");
$mysqli-> select_db("tra");
but none of the tries with OOP will work. I mean, I have the book on my lap, so I am writing it ad litteram. The issue must be elsewhere.
The PHP version is 5.3.8 about the latest one.
The sql query that follows after the connection and selection of the DB (which works if the connection file is procedural, as I say) is:
$sql ="SELECT FName
FROM work_assignment, developer
WHERE developer.country = '".$country."'
AND work_assignment.from_language = '".$from."'
AND work_assignment.into_language = '".$into."'
AND work_assignment.developer_id = developer.developer_id
";
Any ideas as to why?
Thanks a lot
From your comment I surmise you're mixing the mysql and mysqli extensions. They are two separate extensions with nothing in common, except that they both connect to MySQL. If you're connecting to the database using a mysqli object, use that object to run your queries. mysql_query will have no active connection, because you did not establish one using a mysql function.

Categories