PHP Tutorial – Connect to multiple databases with PHP and MySQL
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.
Tags
aggregator codeigniter computer css database developer development facebook fifa fifa 12 football framework freelance google html iPad jquery lamp linux membership system Motherboard mysql myvouchercodes open source php php tutorial resources rossytzoltan rss search engine optimisation seo social media tech forum the guardian tutengine tutorial tutorial search engine tweet twitter ubuntu user system wamp web developer web developer twitter zendTwitter
- RT @mashable 10 Staggering Facts Behind #Apple's Foxconn Factory http://t.co/VJUP8D6e 1 minute ago
- Awful - RT @guardian_sport: New England home jersey unveiled - what's the verdict? http://t.co/SxTRuqsX via @guardian 12 minutes ago
- @mattboucher12 @chris86phillips @craigydibs @sausage_21 @mccloskey1974 sharing the ULTIMATE pic to get us started http://t.co/QcdhtqQy 1 hour ago
- @mattboucher12 @chris86phillips @craigydibs @sausage_21 @mccloskey1974 do we get a demonstration? #shotgunNotVolunteering 1 hour ago
- @mattboucher12 its wednesday 5 hours ago








