mysql connection that re-connects if it's been disconnected


/ Published in: PHP
Save to your folder(s)

usage is simple:
$result = mysqli_query($query,db_conn('local')); for instance.
if written in patterns, this should probably be a singleton, but I haven't bothered converting it - feel free to comment with your modification though!


Copy this code and paste it in your HTML
  1. $local = false;
  2. $master = false;
  3. $host = array('local'=>'localhost','master'=>'192.168.1.1');
  4. function db_conn($type)
  5. {
  6. global $local,$master,$host;
  7. // echo 'in db_conn';
  8. if(${$type} && ${$type}->ping())
  9. {
  10. // echo 'connection already exists and is alive';
  11. return ${$type};
  12. }
  13. else
  14. {
  15. // echo 'connection does not exist, attempting to connect';
  16. ${$type} = new mysqli($host[$type],'user','password','database');
  17. if(${$type})
  18. {
  19. return ${$type};
  20. }
  21. else
  22. {
  23. err('Could not connect to '.${$type}.' database.'.mysqli_connect_error());
  24. return false;
  25. }
  26. }
  27. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.