Skip to page content or Skip to Accesskey List.

Work

Main Page Content

Failover Database Connection With Php Mysql

Rated 2.83 (Ratings: 4)

Want more?

  • More articles in Code
 
Picture of SJBDude7

Stephen Belue

Member info

User since: 19 Feb 2007

Articles written: 1

Imagine, you're connecting to a mySQL database with PHP, but hell, you want a bit more robustness. So why would you want just one database? You'd use a failover right? So if the first database is down or just doesn't connect, it can connect to the next one. Here's how to do that (I'm assuming you're already replicating between databases so that they're roughly in sync).

Here's how you do it. Firstly, you'll have to define some things...

View the comments, they are simple yet... informative.

Now, the one thing that can make all of this come true:

That will connect to the mySQL database with the currently defined variables.

So, obviously, if $connect does that, what would $connect2 do?

It connects to the database! But, oh, it's the second one. Strange, isn't it?

Now, you can check if the database connected or not by checking if its true, or false.

Of course, how does it connect to the second database? Simple!

Now, that's all this really does. It has some mysql_error() stuff in it too, and checks if the url is connection.php?type=1 before executing the code. I basically combined all of that into one script, all you have to do is edit the variables, and do:

Here's the full script:

I was born in Philly. I started to code. I read some books. Yeah.

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.org Evolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.