Query two databases with the same query - php

I need to run the same query on two different databases.
I edited my previous db class obtaining this
class Db {
function connect() {
$db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Error");
mysql_select_db(DB_NAME, $db);
return $db;
}
function connect2() {
$db = mysql_connect(DB_HOST2, DB_USER2, DB_PASSWORD2) or die("Error 2");
mysql_select_db(DB_NAME2, $db);
return $db;
}
function sql_query($sql) {
$result = mysql_query($sql, $this->connect()) or die(mysql_error());
$result2 = mysql_query($sql, $this->connect2()) or die(mysql_error());
} }
Is there a way to avoid the connection to the databases each time? I already tried using $GLOBALS to save the database links but it doesn't seem to work.
Thanks a lot

Take a look at the PHP PDO manual
http://www.php.net//manual/en/book.pdo.php
Using PDO you can make two connections at the same time then you can run two queries on two different databases too ;)

You could use mysql_pconnect() which will establish a persistent connection to your MySQL database. You could then save the link for future reference.
See http://www.php.net/manual/en/function.mysql-pconnect.php for more details.

Related

Pros and cons of connecting more than one database in single script

Let's say user have two databases hosted on single host and I need to connect to both of them so that I can use any table anytime without adding connection code multiple times.
I have implemented this in CodeIgniter with adding authorization details of both databases in database.php file and to load required database with $this->load->database('dbname'); in script.
Now, for core PHP, we can do this like:
mysql_connect ('host','user','password','port','dbname'); // connection with one database.
It was connected with my first database.
Now, I want to connect with second database:
1) I have not closed above connection and connected with second one with
mysql_connect ('host','user','password','port','dbname1');.
2) Would it be bad practice to do so ? Would it consume more objects ? Should we be required to close first one anyhow?
It is not neccessary to open 2 connection just to use tables from 2 databases on the same server. You just need to use the database.table notation. Doing that means that you can even join tables from different databases in the same query
SELECT t1.col1, t1.col2, t2.col2, t2.col2
FROM db1.table1 AS t1 JOIN db2.table1 AS t2 ON t1.col1 = t2.col3
So if you have connected to db1 initially you can use db2 tables and the same if you connected to db2 you can use db1 tables.
Have you tried this?
$mysqli1 = new mysqli("example.com", "user", "password", "database1");
$mysqli2 = new mysqli("example.com", "user", "password", "database2");
Why do you need two connections? The pros/advantages of two databases are actually primarily performance issues. But if you are on the same machine actually the only advantage you have, would be a cleaner separation. So it would be better to use one DB with two different prefixes for the table.
So you seperate the diffent data by prefix and not by DB.
You can do this by following object oriented approach
First of all create connection with two databases:
$Db1 = new mysqli('localhost','root','','database1'); // this is object of database 1
$Db2 = new mysqli('localhost','root','','database2'); // this is object of database 2
$query1 = 'select * from `table_name_of_database1`'; // Query to be run on DB1
$query2 = 'select * from `table_name_of_database2`'; // Query to be run on DB2
$result1 = $Db1->query($query1); // Executing query on database1 by using $Db1
$result2 = $Db2->query($query2); // Executing query on database2 by using $Db2
echo "<pre>";
/* Print result of $query1 */
if ($result1->num_rows > 0) {
while($row = $result1->fetch_assoc()) {
print_r($row);
}
} else {
echo "0 results";
}
/*========================================================*/
/* Print result of $query2 */
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
print_r($row);
}
} else {
echo "0 results";
}
Conclusion: When you want to use database1 use $Db1 object and if you want to use database2 then use $DB2.
I don't think how to connect to 2 DBs simultaneously is the problem, as you have successfully done it ( or know how to do it ). I can gather that from your question. So I won't show how to do this. See other answers if you need to.
But to address your issues directly:
Would it be bad practice to do so ? Generally, you should avoid 2 simultaneous DB connection handles as much as possible. If you only need to get data from one DB and use them to do something on the other, your best bet is to put the data from DB1 into appropriate PHP variables, close the connection; then make the second connection. That would be cheaper than keeping 2 DB connections open at the same time. However, if you are doing something like INSERT INTO db1.table SELECT FROM db2.table AND ALSO NEED TO COMMIT OR ROLLBACK depending on success or failure of some queries, then AFAIK, you need to keep both connections open until your processes are over. You see, there always trade-offs. So you decide based on the need of your application and bear the cost.
As a practical example of this scenario, I once worked on a project where I needed to SELECT a table1, INSERT INTO a table2, if the INSERT succeeds, I delete all the rows from table1, if the DELETE fails, I rollback the INSERT operation because the data cannot live in the two tables at the same time.
Of course, my own case involved only one DB, so no need of a second connection. But assuming the two tables were on different DBs, then that may be similar to your situation.
Would it consume more objects ? No other objects other than the ones pointed out in 1 above, namely the DB connection handles according to your question.
Should we compulsory require to close first one anyhow ? Once again, depending on your application needs.
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
Q: What cons are there to connect with other database without closing previous database?
A: When you connect to a database server physically are assigning resources to interact with you, if two databases are on the same server you would unnecessarily using resources that could be used to address other connections or other activities. Therefore you would be right close connections that do not need to continue using.
Q: Is this a appropriate practice to do so ? What is the best way to do so without opening this connection in every script multiple times ? I want this to get done in core php only as I have already know this in codeigniter.
One way SESSIONS, but you can't store database conections in sessions. Read in PHP.net this Warning: "Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object)." MySQL connections are one such kind of resource.
You have to reconnect on each page run.
This is not as bad as it sounds if you can rely on connection pooling via mysql_pconnect(). When connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. The connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).
Reference:
http://php.net/manual/en/function.mysql-pconnect.php
http://www.php.net/manual/en/intro.session.php
Can't pass mysqli connection in session in php
1) Is it possible to connect with more than one database in one script ?
Yes we can create multiple MySQL link identifier in a same script.
2) It should be not like to close one connection with mysql_close and open new one,rather both connection should open at a time and user can use any table from any of the database ?
Use Persistent Database Connections like mysql_pconnect
3) If it is possible,what can be disadvantage of this ? Will there create two object and this will going to create issue ?
I don't think so it create any issue other than increasing some load on server.
You can use like this
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('abc', $db1);
mysql_select_db('def', $db2);
For Database 1
mysql_query('select * from table1', $db1);
For Database 2
mysql_query('select * from table2', $db2);
The best way to use multiple databases is to use PDO functions
EXAMPLE
// database cobfigurations
$config= array(
// first database
array(
'type'=>'mysql', // DB type
'host'=>'localhost', // DB host
'dbname'=>'database1', // DB name
'user'=>'root', // DB username
'pass'=>'12345', // DB password
),
// second database
array(
'type'=>'mysql', // DB type
'host'=>'localhost', // DB host
'dbname'=>'database2', // DB name
'user'=>'root', // DB username
'pass'=>'987654', // DB password
),
);
// database connections
$mysql=array();
foreach($config as $con)
{
$con=(object)$con;
$start= new PDO($con->type.':host='.$con->host.';dbname='.$con->dbname.'', $con->user, $con->pass, array(
// pdo setup
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
));
if ($start && !empty($start) && !is_resource($start))
$mysql[]=$start; // connection is OK prepare objects
else
$mysql[]=false; // connection is NOT OK, return false
}
/**********************
**** HOW TO USE ****
**********************/
// fetch data from database 1
$data1 = $mysql[0]->query("SELECT id, title, text FROM content1")->fetchAll();
if(count($data1)>0)
{
foreach($data1 as $i=>$result)
{
echo $result->id.' '.$result->title.' '.$result->text.'<br>'
}
}
// fetch data from database 2
$data2 = $mysql[1]->query("SELECT id, title, text FROM content2")->fetchAll();
if(count($data2)>0)
{
foreach($data2 as $i=>$result)
{
echo $result->id.' '.$result->title.' '.$result->text.'<br>'
}
}
If you not use PDO before, please read this short tutorial:
http://www.mysqltutorial.org/php-querying-data-from-mysql-table/
Is practicly same like mysql and mysqli connections but is more advanced, fast and secure.
Read this documentations:
http://php.net/manual/en/book.pdo.php
And you can add more then 2 databases
Use PDO supported by php 5 version instead mysql connect
Here is a simple class that selects the required database automatically when needed.
class Database
{
private $host = 'host';
private $user = 'root';
private $pass = 'pass';
private $dbname = '';
private $mysqli = null;
function __construct()
{
// dbname is not defined in constructor
$this->mysqli = new mysqli( $this->host, $this->user, $this->pass );
}
function __get( $dbname )
{
// if dbname is different, and select_db() is succesfull, save current dbname
if ( $this->dbname !== $dbname && $this->mysqli->select_db( $dbname ) ) {
$this->dbname = $dbname;
}
// return connection
return $this->mysqli;
}
}
// examples
$db = new Database();
$result = $db->db1->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$result = $db->db2->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$result = $db->{'dbname with spaces'}->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$con1 = mysql_connect($hostname, $username, $password);
$con2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $con1);
mysql_select_db('database2', $con2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $con1);
and for database 2 pass the second:
mysql_query('select * from tablename', $con2);
if mysql's user have permission to two database , you can join two table from two database
etc:
SELECT database1.table.title title1,database2.table.title title2
FROM database1.table
INNER JOIN database2.table
ON (database1.table.id=database2.table.id)

PHP - Connect to Multiple MySQL Databases

So I have a PHP page that connects first to my database and does a bunch of stuff using the information from there. Now I want to connect to another database within the same PHP page and access data from there and insert the information into my original database.
The code:
<?php
session_start();
include ("account.php");
include ("connect.php");
....
do stuff here
....
include ("account2.php");
include ("connect2.php");
...
$thing = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1" ;
$thing = mysql_query($thing);
echo "$thing";
....
....
insert information into my database
(From account.php & connect.php files)
....
?>
Everything shows up except for $thing. It says, "Invalid query: Query was empty" but I know the query I used works because when I ran it in the account2 database, I got the results I wanted. Is there something wrong with my logic or is it something else?
You are not mentioning database connection link while executing the query. May be your second database connection is defined after the 1st one in connection.php file. So interpreter is considering 2nd connection while executing the query.
Define the connection link with query,
$thing = mysql_query($thing,$conn); //$conn is your mysql_connect
You can still use the mysql_connect or similar mysql_ functions (procedural way) But all these are now deprecated. You should use mysqli_ (mysql improved) functions or go with the object oriented way.
$conn1 = new mysqli(SERVER1,DB_USER1,DB_PASS1,DB1);
$conn2 = new mysqli(SERVER2,DB_USER2,DB_PASS2,DB2);
if($conn1 ->connect_errno > 0 || $conn2 ->connect_errno > 0){
die('Unable to connect to database server.');
}
Now while executing your query,
$query = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1";
$thing = $conn1 -> query($query); //if it's second connection query user $conn2
Many web applications benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
For your case, i would make 2 persistent connections, store each in it's own variable and then use one whenever i need to. Check it out using the PDO class.
//Connection 1
$dbh1 = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
.
.
.
//Connection 2
$dbh2 = new PDO('mysql:host=localhost;dbname=test2', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
After you finish you first database operation, then you can close the connection using
mysql_close($c) //$c = connection
And again start for next database operation.
private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}

My php script is not using given username/pass/host rather using root#localhost (password: NO)

Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)

PHP Data Base Connection help with mysql

i am new in php and want to know the code for php mysql database connection code
Refer to the PHP documentation for mysql_connect.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
Here is the bare bone of it:
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);
$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);
mysql_query(... , $db2);
More Info:
http://php.net/manual/en/function.mysql-connect.php
MySQL PHP Connect Tutorial
A Detailed Tutorial:
http://www.phpf1.com/tutorial/php-mysql-tutorial.html?page=1
<?php
mysql_connect("localhost", "username", "password") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("test") or die(mysql_error());
echo "Database was selected!<br/>";
?>
Watch also mysqli,it's the "new way" of connecting to mysql
http://php.net/manual/en/book.mysqli.php
it has more functions and there are rumors that in php6 mysql will be deprecated for the mysqli implementation.
you can use it as an object(but if you're new also to OO it may be a little more difficult to understand)like this:
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');//you can also use $db=new mysqli(....) but mysql_connect does the same thing and it's more cler on what it's doing
//--a simple query--
if($result=$db::query('SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',$result->num_rows,'rows<br/>';
while($row=$result->fetch_assoc()){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
$result->close();
}
else//query error
die('MYSQL ERROR:'.$db->error);
or with functions like in mysql
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');
//--a simple query--
if($result=mysql_query($db,'SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',mysql_num_rows($result),'rows<br/>';
while($row=mysqli_fetch_assoc($result)){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
mysql_free_result($result);
}
else//query error
die('MYSQL ERROR:'.mysqli_connect_error());
You can also use a persistent mysql connection prepending 'p:' to the sql host,for example if your host is sql.myhost.com:
$db=mysqli_connect('p:sql.mysqlhost.com','database_username','password','database_name');
Using a persistent connection should give you a great performance boost and mysqli should handle the persistent connection a lot better than the normal mysql extension.
Remember to sanitize the input of your query to avoid SQL INJECTION,you can do like this:
$result=mysql_query($db,"SELECT name,value FROM mytable where name='".mysqli_real_escape_string($input_name)."'");
or using a prepared statement that's a little more complicated and it's better only if you repeat the same command multiple times only changing the input data.

Why would a script not like using MySQLi but is fine with MySQL?

I'm having some issues using mysqli to execute a script with SELECT,DELETE,INSERT and UPDATE querys. They work when using norm mysql such as mysql_connect but im getting strange results when using mysqli. It works fine with a lot of the SELECT querys in other scripts but when it comes to some admin stuff it messes up.
Its difficult to explain without attaching the whole script.
This is the function for modifying...
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $databaseUsername;
global $databasePassword;
global $databaseDebugMode;
$link = #mysql_connect($databaseServer,$databaseUsername,$databasePassword);
#mysql_select_db($databaseName,$link);
$result = mysql_query($sql,$link);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysql_error()."]";
}
$insertId = mysql_insert_id();
return mysql_affected_rows();
}
and heres what I changed it to for mysqli
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $dbUser_feedadmin;
global $dbUser_feedadmin_pw;
global $databaseDebugMode;
$link = #mysqli_connect($databaseServer,$dbUser_feedadmin,$dbUser_feedadmin_pw,$databaseName);
$result = mysqli_query($link, $sql);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysqli_error()."]";
}
$insertId = mysqli_insert_id();
return mysqli_affected_rows();
}
Does that look right?
It isn't actually producing an error but its not functioning in the same way as when using mysql. any ideas?
Here is the way I normally use Mysqli
$mysqli = new mysqli($myServer, $myUser, $myPass, $myDB);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
$result = $mysqli->query($query);
while ($row=$result->fetch_assoc()) {
print_r($row);
}
Note: mysqli is a class, $mysqli is the variable that holds the instance of that class, query is a method of that class that returns a result class that has methods of its own.
You are running all statements at once as far as php is concerned, so functions like affected rows or last inserted id will not work as expected.
(Correct me if I'm wrong I haven't been using mysqli for a while.)
some of the mySqli functions needed some tinkering such as including $link

Categories