how to connect more then one DB in php... but the DB servers are same . but the DB is different. same single page i need to fetch the result from all the 3 db to display. Thank you
Easy: make multiple connections. Each connection returns a resource handle which you assign to a variable. So you just put each connection into it's own variable.
Method 1:
Don't select databases; put the database name before the table:
mysql_connect('localhost','db_user','pssword');
mysql_query('SELECT * FROM database_1.table_name');
Method 2:
$handle_db1 = mysql_connect("localhost","myuser","apasswd");
$handle_db2 = mysql_connect("127.0.0.1","myuser","apasswd");
$handle_db3 = mysql_connect("localhost:3306","myuser","apasswd");
$handle_db4 = mysql_connect("localhost","otheruser","apasswd");
mysql_select_db("db1",$handle_db1);
mysql_select_db("db2",$handle_db2);
mysql_select_db("db3",$handle_db3);
mysql_select_db("db4",$handle_db4);
//do a query from db1:
$query = "select * from test"; $which = $handle_db1;
mysql_query($query,$which);
//do a query from db2 :
$query = "select * from test"; $which = $handle_db2;
mysql_query($query,$which);
Just building more database handles,that's just fine.
http://php.net/mysql_connect, note the parameters
also, if all these DBs share same server, you can just specify particular db using . syntax:
SELECT * FROM db1.table ...
SELECT * FROM db2.table ...
SELECT * FROM db3.table ...
Related
I have multiple db files which contains the same table with different values.
example files:
wifi_16-09-02_09_34_03.db
wifi_16-09-02_09_44_06.db
wifi_16-09-02_09_60_02.db
How can I select all the rows from multiple files?
I only know to do this with one file.
Here is my code:
$dbfile = 'wifi_16-09-02_09_34_03.db';
$db = new SQLite3('dbs/'.$dbfile);
$sql = 'SELECT * FROM wifi';
$results = $db->query($sql);
I am new on SQLite3, any help would be appreciated.
You can simply open the other databases in the same way.
If you want to have all rows in a single query, you need to attach all the other databases to some main database, and use a compound query:
$db->exec("ATTACH 'dbs/wifi_16-09-02_09_44_06.db' AS db2");
$db->exec("ATTACH 'dbs/wifi_16-09-02_09_60_02.db' AS db3");
...
$sql = <<<'SQL'
SELECT * FROM main.wifi
UNION ALL
SELECT * FROM db2.wifi
UNION ALL
SELECT * FROM db3.wifi
SQL;
$results = $db->query($sql);
I'm using CakePHP 3, I need to run a raw SQL query on multiple tables. In CakePHP 2, this could be done by using the query() method on any model ( $this->Messages->query("select..") ).
I need the method that allows me to run a SQL query in CakePHP 3. Following is the code snippet I'm using:
$aumTable = TableRegistry::get('Messages');
$sql = "SELECT (SELECT COUNT(*) FROM `messages`) AS `Total_Count`,
(SELECT COUNT(*) FROM `messages_output`) AS `Total_Output_Count`,
(SELECT COUNT(*) FROM `messages_output` WHERE `is_success`=1) AS `Total_Successful_Output_Count`,
(SELECT COUNT(*) FROM `messages_output` WHERE `is_success`=0) AS `Total_Error_Output_Count`,
(SELECT COUNT(*) FROM `users`) AS `Total_User_Count`;";
// to run this raw SQL query what method should i use? query() doesn't work..
// $result = $aumTable->query($sql); ??
// $result = $aumTable->sql($sql); ??
If you can provide links to CakePHP 3 model documentation where I can find this info, that would be helpful too. I tried searching on google but could only find questions related to CakePHP 2.
First you need to add the ConnectionManager:
use Cake\Datasource\ConnectionManager;
Then you need to get your connection like so:
// my_connection is defined in your database config
$conn = ConnectionManager::get('my_connection');
More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#creating-connections-at-runtime
After that you can run a custom query like this:
$stmt = $conn->execute('UPDATE posts SET published = ? WHERE id = ?', [1, 2]);
More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-queries
And then you are ready to fetch the row(s) like this:
// Read one row.
$row = $stmt->fetch('assoc');
// Read all rows.
$rows = $stmt->fetchAll('assoc');
// Read rows through iteration.
foreach ($rows as $row) {
// Do work
}
More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-fetching-rows
The documentation for this is here: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-queries
But what's not written there is how to execute it. Because it cost me a while, here is the solution for that:
1.You need to add
use Cake\Datasource\ConnectionManager;
2.init the ConnectionManager (as mentioned above)
$conn = ConnectionManager::get('my_connection');
3.Execute your SQL with something like this
$firstName = $conn->execute('SELECT firstname FROM users WHERE id = 1');
The question is already very old, but I still find it frequently.
Here is a solution for CAKEPHP 3.6 and (short) for newer PHP Versions.
It is not necessary to use the ConnectionManager get function and often it does not make sense, as the connection name may not be known at all. Every table has its / a connection which one can get with getConnection ().
If you are already in the Messages Table (src/Model/Table/MessagesTable.php), you can simply use the Connection
$con = $this->Messages->getConnection();
If you are not there (what your code would suggest with TableRegistry::get(), you can do that with this table as well
// $aumTable is declared in question
$con = $aumTable->getConnection();
then you can execute a RAW query as shown above:
$result = $con->execute ();
// short
$result = $this->Messages->getConnection()->execute ('Select * from ...')
// or ($aumTable is declared in question)
$result = $aumTable->getConnection()->execute ('Select * from ...');
For a particular process I am storing a list of mysql queries in Database using php variables for condition data retrieval.
I'm storing:
Select count(1) from Users where user='$user1'
I have written a script where I first initialize: $user1="XYZ";
Then I select the above query from database and try to execute it again using mysql_query.
But the value of $user1 is not getting initialized as required.
Please fidn below the psuedo code:
$user1="xyz";
//selecting the query
$select_table="SELECT * FROM `test`";
$result_table=mysql_query($select_table);
$select_query=mysql_result($result_table,$j,"Select_Query");
$panelinttable_result=mysql_query($select_query);
This will not work as when you retrieve data, $user1 will not be a variable but a part of string "Select count(1) from Users where user='$user1'".
Using str_replace() should work :
$select_query = mysql_result($result_table,$j,"Select_Query");
$select_query = str_replace('$user1', $user1, $select_query);
$panelinttable_result=mysql_query($select_query);
Also, why are you storing those queries in database ?
It would be better to make functions for this.
function userExists($user) {
$query = mysql_query("Select count(1) from Users where user = '".$user."'");
return mysql_num_rows($query);
}
I have 2 databases on the same server with 2 identical tables.
What I want to do is select all records from both tables and join them in one array.
I've been messing around with the script below. For some reason it returns the records of db2.tbl twice and doesn't return the db1.tbl records at all. When I try to select the data from a single database is works fine for both of them. Does any one see the problem?
<?PHP
require_once("config.php");
$conn = #mysql_connect($dbhost, $dbuser, $dbpass)or die ('Error connecting to mysql server'.mysql_error());
$q = mysql_query("SELECT * FROM db1.tbl JOIN db2.tbl");
var_dump(mysql_num_rows($q));
while($arr = mysql_fetch_assoc($q)){
var_dump($arr);
}
?>
Is this what you want ? All records from database1 followed by all records from database2:
$q = mysql_query("SELECT * FROM db1.tbl UNION SELECT * FROM db2.tbl");
I assume the user you are connecting with has access to both databases.
Your query should work. However add tilt(`) to your database name table name. Execute the query first in mysql see whether it is ok than execute with php.
I would like execute a query like this one in symfony using the Propel ORM:
UPDATE ADS SET HITS=HITS+1 WHERE ID=10;
I know that Propel API can let me set a previously fixed value for a column of a given record, but I definitely don't want to retrieve the column value first before issuing an update query since there are concurrent access.
Please, how could I achieve this?
Thanks.
This works in Symfony 1.3/1.4:
in AdsPeer:
public static function incrementHits($id)
{
$con = Propel::getConnection(AdsPeer::DATABASE_NAME);
$query = 'UPDATE hits SET hits + 1 WHERE id = '.$id;
sfContext::getInstance()->getLogger()->crit($query);
$stmt = $con->prepare($query);
$rs = $stmt->execute();
}
To use:
AdsPeer::incrementHits($id);
HTH
Mike
If you like you can do a Select using SQL in propel.
Here's an example:
class BookPeer extends BaseBookPeer {
.
.
.
/**
* Get just the Books that have not been reviewed.
* #return array Book[]
*/
function getUnreviewedBooks() {
$con = Propel::getConnection(DATABASE_NAME);
// if not using a driver that supports sub-selects
// you must do a cross join (left join w/ NULL)
$sql = "SELECT books.* FROM books WHERE ".
"NOT EXISTS (SELECT id FROM review WHERE book_id = book.id)";
$stmt = $con->createStatement();
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM);
return parent::populateObjects($rs);
}
You can try this with update as well.