how to work with multiple database - php

I am working on one company internal web software and in this I have given forum option for internal employee.Now I have to add second company to forum so that second company employee can also give some comment in forum.I have two database one for my company internal and second is second company database.
Please Help me how can I Implement this???

Always use resource returned by mysql_connect() so you know what database you use
// database 1
$db1 = mysql_connect();
// database 2
$db2 = mysql_connect();
// query db1
mysql_query($query,$db1);
Also try reading the docs about it

It depends on what database you are using..,,
and try to read some mysql function cause theres a function for linking databases..

You should use 2 (3, 4, 5 ...) db connections.
If your bases is not MySql only, you can use PDO extension:
$db1 = new PDO($param1, $param2, $param3);
$db2 = new PDO($param4, $param5, $param6);
And then you can use any of them, e.g.:
$db2->exec();

Related

Laravel - Where Condition on Multiple Database

I'm using laravel with multiple DB connection. Oracle and PostgreSQL. I can do query from both of instance.
But the problem is I have to look inside my Oracle DB WHERE NOT EXISTS on my postgreSQL.
This is my current Query :
DB::connection('ora')->table('ora_purch')
->whereExists(function($query)
{
$query->select(DB::connection('pgs')->raw(1))
->from('pg_purch')
->whereRaw('ora_purch.id = pg_purch.id');
})
->get();
From this query, I get error "database pg_purch is not exists". It's just like laravel reads pg_purch as an oracle instance.
I also do simulation with the same query and the same instance (multiple database on postgreSQL only), the query is fine and produces correct data.
Is it possible to makes the laravel reads pg_purch refer to the connection?
Or maybe i've missing something?
Please advise, thank you.
Your code generates query like this:
SELECT * FROM ora_purch WHERE EXISTS (SELECT 1 FROM pg_purch WHERE ora_purch.id = pg_purch.id);
And make it with "ora" connection, ignoring "pgs" connection.
You can't use multiple connections inside one query.
Try to split them:
$ids = DB::connection('pgs')->from('pg_purch')->pluck('id');
$result = DB::connection('ora')->from('ora_purch')->whereIn('id', $ids)->get();

CREATE and DROP TABLE using Zend Adapter

I'm trying to do some SQL queries using Zend adapter. The code that I'm trying to use is something like this:
$result = $this->$db->getConnection()->exec('CREATE TABLE TEST');
and I know that $db is set and works properly, because I can run other commands such as
$this->$db->listTables(); or
$result = $this->$db->fetchAssoc("SHOW COLUMNS FROM " .$schema);
As I was reading through Zend documentation, it was mentioned that some database transactions that are not prepared should be used through the first example (e.g. exec("...") ), but apparently I have problems running those.
Any thoughts?
This should work ...
$db = Zend_Db_Table::getDefaultAdapter();
$db->query('CREATE TABLE wolf (tag VARCHAR(9))');

Create a MongoDB database with PHP

The only way I found to do this is:
$mongo->selectDB('new_db')->createCollection('tmp_collection');
$mongo->selectDB('new_db')->dropCollection('tmp_collection');
Doing just $mongo->selectDB('new_db') actually doesn't work.
Got any idea?
You'll need to run at least one command on the Database before it is created ...
This command can be run before you add any Collections ... so you can merely list (the nonexistent) Collections.
<?php
$connection = new Mongo();
$db = $connection->foo;
$list = $db->listCollections();
foreach ($list as $collection) {
echo "$collection </br>";
}
?>
Your new Database should now exist, with no user Collections created yet.
Technically, you don't need to manually create databases or collections in MongoDB due to its schemaless "lazy" way of creating databases and collections.
I understand if you're coming from an SQL world this doesn't make much sense. You may want to ask yourself though, "If it automatically creates a collection or database for me on the fly, is there really a need to define it ahead of time?"

Zend Framework slow connect to Mysql [duplicate]

I am creating a web site using php, mysql and zend framework.
When I try to run any sql query, page generation jumps to around 0.5 seconds. That's too high. If i turn of sql, page generation is 0.001.
The amount of queries I run, doesn't really affect the page generation time (1-10 queries tested). Stays at 0.5 seconds
I can't figure out, what I am doing wrong.
I connect to sql in bootstrap:
protected function _initDatabase ()
{
try
{
$config = new Zend_Config_Ini( APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV );
$db = Zend_Db::factory( $config -> database);
Zend_DB_Table_Abstract::setDefaultAdapter( $db );
}
catch ( Zend_Db_Exception $e )
{
}
}
Then I have a simple model
class StandardAccessory extends Zend_DB_Table_Abstract
{
/**
* The default table name
*/
protected $_name = 'standard_accessory';
protected $_primary = 'model';
protected $_sequence = false;
}
And finally, inside my index controller, I just run the find method.
require_once APPLICATION_PATH . '/models/StandardAccessory.php';
$sa = new StandardAccessory( );
$stndacc = $sa->find( 'abc' );
All this takes ~0.5 seconds, which is way too long. Any suggestions?
Thanks!
Tips:
Cache the table metadata. By default, Zend_Db_Table tries to discover metadata about the table each time your table object is instantiated. Use a cache to reduce the number of times it has to do this. Or else hard-code it in your Table class (note: db tables are not models).
Use EXPLAIN to analyze MySQL's optimization plan. Is it using an index effectively?
mysql> EXPLAIN SELECT * FROM standard_accessory WHERE model = 'abc';
Use BENCHMARK() to measure the speed of the query, not using PHP. The subquery must return a single column, so be sure to return a non-indexed column so the query has to touch the data instead of just returning an index entry.
mysql> SELECT BENCHMARK(1000,
(SELECT nonindexed_column FROM standard_accessory WHERE model = 'abc'));
Note that Zend_Db_Adapter lazy-loads its db connection when you make the first query. So if there's any slowness in connecting to the MySQL server, it'll happen as you instantiate the Table object (when it queries metadata). Any reason this could take a long time? DNS lookups, perhaps?
The easiest way to debug this, is to profile your sql queries. you can use Firephp (plugin for firebug) see http://framework.zend.com/manual/en/zend.db.profiler.html#zend.db.profiler.profilers.firebug
another way to speed up things a little is to cache the metadata of your tables.
see: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.metadata.caching
Along with the above suggestions I did a very unscientific test and found that the PDO adapter was faster for me in my application (I know mysqli is supposed to be faster but maybe it's the ZF abstraction). I show the results here (the times shown are only good for comparison)

PHP / SQLite - Copying a table from disk to memory

I have a sqlite3 database on my harddrive (file.db) with 5 tables.
I'd like to copy 3 of these tables to an in-memory database (:memory:).
Is there a simple way to do so using PHP5's PDO format?
Not a pdo-specific solution that may or may not be sufficient in your case:
create a :memory: database
Attach the existing database file
CREATE TABLE ... AS SELECT * FROM ...
Detach the database file
edit: an example
First an example database stored in mydb.sq3
<?php
$pdo = new PDO('sqlite:mydb.sq3');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE foo(x INTEGER PRIMARY KEY ASC, y, z)');
$stmt = $pdo->prepare("INSERT INTO foo (x,y,z) VALUES (:x,:y,:z)");
$stmt->bindParam(':x', $x);
$stmt->bindParam(':y', $y);
$stmt->bindParam(':z', $z);
for($x=0; $x<100; $x++) {
$y = $x*2;
$z = $x*2+1;
$stmt->execute();
}
Now we have a :memory: database and want to transfer the table foo
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('ATTACH "mydb.sq3" as filedb');
$pdo->exec('CREATE TABLE bar AS SELECT * FROM filedb.foo');
$pdo->exec('DETACH filedb');
Done. But let's take a look at the sqlite_master table
foreach($pdo->query('SELECT sql FROM sqlite_master') as $row) {
echo $row['sql'];
}
this prints
CREATE TABLE bar(x INT,y,z)
The INTEGER PRIMARY KEY ASC declaration is lost. Might be sufficient though....
If that's what you need to do, then VolkerK's answer is the one I'd provide, but I feel that I have to point out that you're going to read the contents of those tables into memory each time you run that code (every time that page loads?), so it might be better just to query the data files from disk.
Note that one could always use some kind of shared memory mechanism (e.g. APC, memcache, etc..) to keep sqlite's in-memory databases persistent across connections.
You can dump the database at the end of the connection, save it as apc variable and then load and run again from apc at the beginning of the next execution.
Using the method outlined by VolkerK roughly doubled the performance of my code when using a ~150Mb sqlite database.
Loading the database into an in-memory sqlite db didn't require any other changes to my existing code.
My use case was batch processing data so I didn't have to deal with the problems Wez Furlong highlights.
Reading the data into memory was surprisingly fast. The whole 150Mb was loaded into memory from SSD in less than two seconds. It seemed too good to be true so I checked and rechecked the data.
Many thanks to VolkerK for a magic solution!
I also found that when I indexed the in-memory tables my queries executed three times faster
//adapting VolkerK's example...
//loop through tables from the local sqlite db
$tables = array('companies', 'directors', 'previous_names');
foreach($tables as $table){
//load each table into memory
$pdo->exec("CREATE TABLE $table AS SELECT * FROM filedb.$table");
//index each table on the relevant columns
$pdo->exec("CREATE INDEX IF NOT EXISTS `".$table."_company_number`
ON $table (`company_number`);");
}
If you need a small database for tests, you may export your databse to an SQL file and then execute it as a single query in PHP:
class EphemeralPDO extends \PDO {
public function __construct() {
parent::__construct('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$queries = file_get_contents(__DIR__ . '/database.export.sql');
$this->exec($queries);
}
}

Categories