Firstly, I know that this system shouldn't be using mysql_ functions anymore, but it does.
The system is connecting to two databases. Before running a query, it is selecting the correct database on which to run the query using mysql_select_db(). The correct database is 'database2'. The connection to the database itself works, and the mysql_select_db function is returning true/1.
The code works locally but does not work on the server...
Here is an example of a failing query...
global $DBtwo;
mysql_select_db('database2', $DBtwo);
$sql = "INSERT INTO table
(Column1, Column2, Column3)
VALUES
('Value1', 'Value2', 'Value3')";
$result = mysql_query($sql, $DBtwo);
die(mysql_error());
This script returns the following output...
Table 'database1.table' doesn't exist
The error suggests that the query is being executed on database1, not database2. However database2 is being successfully selected before the query is run.
As mentioned, this error only occurs on the server. Running locally the queries work and the correct databases are used.
Any suggestions or pointers would be very welcome. Cheers.
The comment from Marc B solved my problem so credit goes to him.
The mysql_error function was returning misleading info as it was not being passed a resource.
The mysql_select_db was actually working. It gave the impression of not working via a combination of not passing the correct resource to mysql_error. On top of that a mysql_insert_id() was not working for the same reason, leading the function overall to return false.
I now feel stupid, but far less annoyed. Many thanks!
I'm having a weird issue with connecting to the master database twice.
$devdb01 = $this->load->database('master',true);
$dbstate = $this->load->database('mastercheck',true);
I have 2 different connection id's but it seems if i'm running a query on the master database it won't execute another query even though its a separate database connection. Basically i'm trying to use a SP that runs a restore database and then run another query checking if the database is still in a restoring state.
I run the queries like the following:
$dbresult=$devdb01->query($query);
$dbcheck=$dbstate->query($checkquery);
echo $devdb01->conn_id;
echo $dbstate->conn_id;
$query = "EXECUTE master..sqlbackup '-SQL \"RESTORE DATABASE $dbname FROM DISK = [$restoredir$backupselected] WITH REPLACE, MOVE [$dataname] TO [$datadir$dbname$dataprepend] , MOVE [$logname] TO [$logdir$dbname$logprepend]\"'";
$dbresult=$devdb01->query($query);
$checkquery="SELECT state_desc from sys.databases where [name]='$dbname'";
$dbcheck=$dbstate->query($checkquery);
var_dump($dbcheck);
I just get an output of bool(false) for that var_dump. I verified that the connection id's are different after connecting to the database.
When I try to check the result of the 2nd query I get an error saying i'm calling a member function on a non-object so it must not be executing the query. If I reverse the order it will execute the other query like expected.
I can't tell if this is a PHP limitation? I'm using code igniter so it could be something related to that as well. I tested with SQL Management Studio and it works fine in separate query windows connecting multiple times to the master database. What i'm trying to accomplish is to come up with a way to run this first query then not do anything until I know that query is completed first.
Update
It appears if I turn off Persistent Database connections by disabling pconnect it will use the same connection twice.
This is the output from the connection id with pconnect set to false:
Resource id #52Resource id #52
So, I created a query in PhpMyAdmin to pick one random online member that is part of a certain group. It works fine in PhpMyAdmin and does exactly what I want. However, when I run this query using PHP it does not return anything. I simply get 'NULL' when I use var_dump($result).
$sql= "SELECT
ow_base_user_online.userId,
ow_base_authorization_user_role.roleId
FROM
ow_base_user_online
INNER JOIN ow_base_authorization_user_role ON ow_base_authorization_user_role.userId = ow_base_user_online.userId
WHERE
ow_base_authorization_user_role.roleId = 14
ORDER BY
RAND()
LIMIT 1";
$result = OW::getDbo()->queryForList($sql);
Please, does anyone have any ideas?
Please does anyone have any ideas?
Yes, use error reporting from your mysql query and see what it returns. Check PHP errors too (can get auth warnings to show something daft like bad user/password etc).
Also, for testing, try removing the class you use and stick the DB connection code above that query and query all direct from a test script. If it works fine, then your query is ok, as is the connection and credentials.
From there you can work backwards checking the class you have.
I have two DB real and backDB. I would like to copy everything from one to a other with SQL... it seems not that easy. If anyone could help me out. Here is my code:
$newdbsql="CREATE TABLE $newdb LIKE $actdbname.`$acttable`";
$newresult = mysql_query($newdbsql, $bckconn) or die(mysql_error());
// copy all the data
$query = "INSERT INTO $newdb SELECT * FROM $actdbname.$acttable WHERE $acttable.azon < $upto";
$result = mysql_query($query, $bckconn) or die(mysql_error());
I've been fighting with it but I can't get it right... thanks
Update:
I can connect both DB and I can do simple selects as well. But where I want to read from A and copy to BackupDb it always connect just to one DB.
Error message:
SELECT command denied to "backup"user on the real DB...
Important info: I am on shared host so it is not that easy:)
You just need to grant SELECT permissions to the backup database user to the regular database:
GRANT SELECT ON `$actdbname`.* TO `backup`#`localhost`;
For best security, it isn't recommended to grant anything other than SELECT, since no other permissions should be needed.
Warning:
Please, don't use mysql_* functions to write new code. They are no longer maintained and the community has begun the deprecation process. See the red box?
Instead, you should learn about prepared statements and use either PDO or MySQLi. This article should give some details about deciding which API to use. For PDO, here is a good tutorial.
To replicate the database without using MySQL's internal replication feature, you can use the CREATE TABLE foo LIKE bar; and INSERT INTO foo SELECT * FROM bar; statements.
The first line will create a new table named foo using the exact same structure what bar had originally, and the second line will help you copy the whole contents of bar into foo.
Edit:
The table names can be said as foo, it will mean the foo table in your current database. But you can say baz.foo, which will mean the foo table in your baz database. Of course, your users needs the required privileges to have on both databases. The following code works:
mysql_connect("localhost", "username", "password");
mysql_select_db("original");
mysql_query("CREATE TABLE backup.foo LIKE original.bar");
mysql_query("INSERT INTO backup.foo SELECT * FROM original.bar");
mysql_close();
In our last episode (How I constructed a cross database query in MySQL) I learned how to construct a cross database query in MySQL. This worked great but when our hero tried to use this newfound knowledge in PHP he found his best friend FAIL waiting for him.
I took a look at mysql_select_db for PHP. This seems to imply that if I want to use MySQL with PHP, I have a couple of choices:
Use mysql_select_db but be stuck with only using one db at a time. This is our current setup and putting a database as a namespace identifier doesn't seem to work (it works fine in the MySQL shell so I know it's not a problem with our MySQL server setup).
Don't use mysql_select_db. From some of the examples I've seen, this seems to mean that I have to specify the db for every query that I make. This makes sense since I haven't used mysql_select_db to tell PHP what db I want to access. This also makes sad since I don't want to go through all my code and prepend a db name to every query.
Is there something better than this? Is there a way for me to do a cross db MySQL query in PHP without having to something crazy like (2)?
CLARIFICATION: None of the proposed answers actually let me do a cross db query. Instead, they allow me to access two different DBs separately. I want a solution that allows me to do something like SELECT foreign_db.login.username, firstname, lastname from foreign_db.login, user where ... NOT just make different queries to different DBs. For what it's worth, (2) doesn't work for me.
You will need your databases to run on the same host.
If so, you should be able to use mysql_select_db on your favourite/default db and manually specify a foreign database.
$db = mysql_connect($hots, $user, $password);
mysql_select_db('my_most_used_db', $db);
$q = mysql_query("
SELECT *
FROM table_on_default_db a, `another_db`.`table_on_another_db` b
WHERE a.id = b.fk_id
");
If your databases run on a different host, you won't be able to join directly. But you can then make 2 queries.
$db1 = mysql_connect($host1, $user1, $password1);
$db2 = mysql_connect($host2, $user2, $password2);
$q1 = mysql_query("
SELECT id
FROM table
WHERE [..your criteria for db1 here..]
", $db1);
$tmp = array();
while($val = mysql_fetch_array($q1))
$tmp[] = $val['id'];
$q2 = mysql_query("
SELECT *
FROM table2
WHERE fk_id in (".implode(', ', $tmp).")
", $db2);
After reading your clarification, I am under the impression that you actually want to query tables residing in two separate MySQL server instances. At least, your clarification text:
SELECT foreign_db.login.username, firstname, lastname from foreign_db.login, user where
suggests that you want to run one query while being logged in as two users (which may or may not reside on the same mysql server instance).
In your question, you said you wanted to query data from two different databases, but it is important to realize that one MySQL instance can have many, many databases. For multiple databases managed by the same mysql instance, the solution proposed in the question you linked to simply works: just prefix the table name with the name of the databases, separating database and table names with a dot: <db-name>.<table-name>.
But, like i pointed out, this only works if:
all databases you access in one query reside on the same server - that is, are managed by the same MySQL instance
the user that is connected to the database has the right privileges to access both tables.
Scenario1: databases on same host: grant appopriate privileges and qualify table names
So if the tables actually reside on the same mysql instance, there is no need for a second login or connection - simply grant the database user you use to connect to the datbase the appropriate privileges to select from all tables you need. You can do that with the GRANT syntax, documented here: http://dev.mysql.com/doc/refman/5.1/en/grant.html
For example, GRANT SELECT ON sakila.film TO 'test'#'%' will allow the user test#% to select data from the film table in the sakila database. After doing that, said user can refer to this table using sakila.film (so-called qualified table name), or if the current database is set to sakila, simply as film
Scenario2: databases managed by different MySQL instances: FEDERATED engine
If the tables you want to access are actually managed by two different MySQL instances, there is one trick that may or may not work, depending on your configuration. Since MySQL 5.0 mysql supports the FEDERATED storage engine. This lets you create a table that is not actually a table, but a peephole to a table on a remote server. This engine is documented here: http://dev.mysql.com/doc/refman/5.1/en/federated-storage-engine.html
For example, if you know there is this table in the misc database on the remote host:
CREATE TABLE t (
id int not null primary key
, name varchar(10) not null unique
)
you can make a local 'pointer' to that remote table using this:
CREATE TABLE t (
id int not null primary key
, name varchar(10) not null unique
)
ENGINE = FEDERATED
CONNECTION='mysql://<user>#<remote-server>:<remote-port>/misc/t';
Unfortunately, the FEDERATED engine is not always available, so you have to check first if you can even use that. But suppose it is, then you can simply use the local table t in your queries, just like any other table, and MySQL will communicate with the remote server and perform the appropriate operations on the physical table on the other side.
Caveat: there are several optimization issues with FEDERATED tables. You should find out if and to what extent these apply to you. For instance, applying a WHERE to a federated table can in many cases result in the entire table contents being pullled over the wire to your local server, where the actual filtering will be appplied. Another issue is with table creation: you have to be very sure that the definitions of the federated table and the table it is pointing to match exacty, except for the ENGINE clause (and CONNECTION). If you have for example a different character set, the data may arrive completely garbled after travelling over the wire.
If you want to use FEDERATED tables, do read this article http://oreilly.com/pub/a/databases/2006/08/10/mysql-federated-tables.html to decide if its right for your particular use case.
If you think you do need it, I have a utility to create federated tables here: http://forge.mysql.com/tools/tool.php?id=54
Scenario3: can't use FEDERATED, but tables on different MySQL instances
Finally, if you have tables on different MySQL instances, but cannot for some reason use the federated table engine, your a out of luck I'm afraid. You are simply going to have to execute queries to both MySQL instances, receive the results and do something intelligent with it in PHP. depending on your exact requirements, this may be a perfectly viable solution
I guess you need to decide for yourself which part of my answer best appeals to your problem, and add a comment in case you need more help. TIA Roland.
A solution might be to :
use mysql_select_db to select the "default" (i.e. most used) database
and specify the DB name only in queries that have to work with the "second" (i.e. least used) database.
But this is only a viable solution if you have one DB that's more used than the other...
Out of curiosity : did you try establishing several connections to your DB server -- i.e. one for each database ?
You might be able to :
connect to the first DB with mysql_connect, and, then, select the first DB with mysql_select_db
and, then, connect to the second DB, passing true for the new_link parameter of mysql_connect if necessary, and, then, selecting the second DB with mysql_select_db
Then, work with the connection identifier returned by the first, or second, call to mysql_connect, depending on which DB you want to issue queries.
As a sidenote : the "best" / "cleanest" solution would be not using mysql_* functions directly, but working with some kind of ORM framework, that would have the ability to work with several DB connections at the same time (not sure, but maybe Doctrine can do that -- it's a real good ORM)
I set up tables in separate test databases as follows:
mysql> use test;
mysql> create table foo as select 42 as id from dual;
mysql> create database test2;
mysql> use test2;
mysql> create table bar as select 42 as id from dual;
I ran the following PHP script with MySQL 5.1.41 and PHP 5.3.1 on Mac OS X:
<?php
$link = mysql_connect('localhost', 'root', 'XXXX')
or die('There was a problem connecting to the database.');
mysql_select_db('test');
$sql = "SELECT * FROM foo JOIN test2.bar USING (id)";
if (($result = mysql_query($sql)) === FALSE) {
die(mysql_error());
}
while ($row = mysql_fetch_array($result)) {
print_r($row);
}
This test succeeds. The result is the join between the two tables in separate databases.
You should always be able to select from table(s) qualified by their respective database names in SQL. The mysql API in PHP does not restrict you to querying one database.
You should always be able to omit the database qualifier for the "current" database, which you declare with mysql_select_db().
Maybe this is the code that you want
//create links
$link1 = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$link2 = mysql_connect('localhost', 'mysql_user', 'mysql_password');
//set db on every link
mysql_select_db('foo', $link1);
mysql_select_db('bar', $link2);
//do query with specified link
$result1 = mysql_query($query1,$link1);
$result2 = mysql_query($query2,$link2);
Note that we didn't do a mysql_select_db between queries , and we didn't use the database name in the query either.
Whenever you are SELECTing from multiple tables you have to sepcify an alias. So it's pretty simple from there:
SELECT
a.id, a.name, a.phone,
b.service, b.provider
FROM
`people` AS a,
LEFT JOIN
`other_database`.`providers` AS b ON a.id = b.userid
WHERE
a.username = 'sirlancelot'
As others on this page have mentioned, the database must be on the same host and instance. You cannot query a database from another server with this syntax.
The less verbose option you have is provided by the MySQL Manual itself:
The following example accesses the
author table from the db1 database and
the editor table from the db2
database:
USE db1;
SELECT author_name, editor_name FROM author, db2.editor
WHERE author.editor_id = db2.editor.editor_id;
You can use option two: "Don't use mysql_select_db" and then use mysql_db_query instead of mysql_query ... which is a simple find and replace.
Best of luck!
I've just tried this simple code in my computer and it works perfectly:
<?php
$conn = mysql_connect('localhost', 'root', '....');
mysql_select_db('aliro');
$sql = 'select * ' .
'from aliro_permissions a ' .
'left join cmsmadesimple.cms_permissions b on a.id=b.permission_id ';
$res = mysql_query($sql)
or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
print_r($row);
}
?>
(Of course, the query itself is meaningless, it's just an example.)
So I can't really see what your exact problem is. If you want a syntax that's simpler that this, you'll have to provide an example of what kind of SQL you want to write.