Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can make multiple calls to <code>mysql_connect()</code>, but if the parameters are the same you need to pass true for the '<code>$new_link</code>' (fourth) parameter, otherwise the same connection is reused. For example:</p> <pre><code>$dbh1 = mysql_connect($hostname, $username, $password); $dbh2 = mysql_connect($hostname, $username, $password, true); mysql_select_db('database1', $dbh1); mysql_select_db('database2', $dbh2); </code></pre> <p>Then to query database 1 pass the first link identifier:</p> <pre><code>mysql_query('select * from tablename', $dbh1); </code></pre> <p>and for database 2 pass the second:</p> <pre><code>mysql_query('select * from tablename', $dbh2); </code></pre> <p>If you do not pass a link identifier then the last connection created is used (in this case the one represented by <code>$dbh2</code>) e.g.: </p> <pre><code>mysql_query('select * from tablename'); </code></pre> <p><strong>Other options</strong></p> <p>If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:</p> <ul> <li>Keep one connection open and call <code>mysql_select_db()</code> to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.</li> <li>Specify the database name when you reference tables within your queries (e.g. <code>SELECT * FROM database2.tablename</code>). This is likely to be a pain to implement.</li> </ul> <p>Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload