Quantcast
Channel: Ross Tanner » tutorial
Viewing all articles
Browse latest Browse all 2

PHP Tutorial – Connect to multiple databases with PHP and MySQL

$
0
0

A nice and simple PHP tutorial today where I will show you how to connect to multiple MySQL databases at once using PHP. I’m sure when you first considered the option of multiple connections you thought it wasn’t possible, difficult to do or there is a long winded way of doing it (such as disconnecting and re-connecting each time you want to make a query). This is untrue. All that you need to do is define a new connection and save it as a seperate resource. So, a simple one-database connection would look like this:

<?php

    // connect to the database server
    $conn = mysql_connect("HOST", "USERNAME", "PASSWORD");

    // select the database to connect to
    mysql_select_db("DATABASE", $conn);

    // query the database
    $query = mysql_query("SELECT * FROM users", $conn);

    // close the database connection
    mysql_close($conn);

?>

Now if you were to have a second connection, instead of disconnecting from $conn and re-connecting as a seperate connection, you can keep the first one alive and create a second. Just like follows:

<?php

    // connect to the database server
    $conn = mysql_connect("HOST", "USERNAME", "PASSWORD");

    // select the database to connect to
    mysql_select_db("DATABASE", $conn);

    // connect to the second database server
    $conn2 = mysql_connect("HOST", "USERNAME", "PASSWORD");

    // select the database to connect to
    mysql_select_db("DATABASE", $conn2);

    // query the first database
    $query = mysql_query("SELECT * FROM users", $conn);

    // query the second database
    $query = mysql_query("SELECT * FROM articles", $conn2);

    // close the database connections
    mysql_close($conn);
    mysql_close($conn2);

?>

As you can see I have two open connections and I am interacting with both databases. At the end I simply close both connections. It is as simple as that. Any questions please don’t hesitate to ask in the comments section below. Alternatively ping me a message or a tweet on Twitter – @rossytzoltan.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles



Latest Images