Main Page Content
Failover Database Connection With Php Mysql
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: