-2

I am trying to make a query on two different databases with php and mysql. You can see my approach bellow, but it does not work. Both the queries are being executed on the first database. Why does this happen?

mysql_connect(HOST,USER,PASSWORD);
mysql_select_db(DB_1);

mysql_query("some query");

mysql_select_db(DB_2);

mysql_query("some query");
user3141607
  • 61
  • 1
  • 10
  • 1) better upgrade your mysql_* code (deprecated) to mysqli_* or pdo. 2) to see what you've done wrong we need your code or at least part of it. 3) you can always not connect to db and use (example) SELECT * FROM dbname.dbtable on each Query. – Marco Mura Nov 18 '14 at 15:55
  • Use `error_reporting(E_ALL);` and `ini_set('display_errors',1);`. Then add a print error condition to the connect, select and query. – vaso123 Nov 18 '14 at 15:56
  • 1
    Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide. – TRiG Nov 18 '14 at 15:56
  • Possible duplicate: http://stackoverflow.com/questions/274892/how-do-you-connect-to-multiple-mysql-databases-on-a-single-webpage –  Nov 18 '14 at 15:56
  • 2) that is the code. 3) that would destroy my whole application :( – user3141607 Nov 18 '14 at 15:56

2 Answers2

3

You should make sure the resource is updated and used:

$link = mysql_connect(HOST,USER,PASSWORD);
mysql_select_db(DB_1, $link);

mysql_query("some query", $link);

mysql_select_db(DB_2, $link);

mysql_query("some query", $link);
RichardBernards
  • 3,146
  • 1
  • 22
  • 30
1

Use an absolute query:

SELECT field FROM db1.table ...
SELECT field FROM db2.table ...

e.g. you don't need to use select_db(). That merely sets the DEFAULT database to use, but you can easily query other databases by using the absolute db.table.field naming convention.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Thanks that's a good point. Sadly it would mean too much of a change in my code to do it now. At least I'll know I can do that. – user3141607 Nov 18 '14 at 15:59