• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Set database connection timeout in CodeIgniter 3

#1
Lightbulb 
We are working with 2 databases, our local database and an external database. But now our external database is down (we're still under development so it's good we came across this issue) and it now tries to connect to the external database for 30 seconds, how can I change the connection timeout of the Database to something like 1 - 2 seconds? I am using Codeigniter with the PDO drivers on my databases. Is there anyone with a clean solution for this problem?

I have also asked this question on stackoverflow, but no luck there, link to it --> http://stackoverflow.com/questions/32616...eigniter-3
Reply

#2
Since CodeIgniter doesn't support this as a configuration option, you'll most likely have to modify the pdo_driver's db_connect() method to add PDO::ATTR_TIMEOUT to the options array with the timeout value you want:

PHP Code:
public function db_connect($persistent FALSE)
{
    
$this->options[PDO::ATTR_PERSISTENT] = $persistent;
    
// Add the desired timeout:
    
$this->options[PDO::ATTR_TIMEOUT] = $timeout

However, even the PHP manual says that the different PDO drivers will interpret this setting differently, as some interpret it as a connection timeout while others interpret it as a read timeout interval. I would imagine such differences would also make it difficult to get something like this supported in CI.
Reply

#3
Thanks for the response! Is there maybe a more clean way to achieve this?
I rather do not touch the core files, only if really needed.
Reply

#4
The only other way I can really think of would be to set it in the configuration of your database or PHP itself, if possible. You'll have to check the documentation of each to find any available methods of doing so.
Reply

#5
Answer is take from the stackoverflow question and it was as easy as this:


Code:
It is not a documented feature, but you can do this from the database config file (application/config/database.php) by adding options setting e.g.:

$db['default']['options'] = array(PDO::ATTR_TIMEOUT => 5);
The other settings which use the same internal mechanism (e.g. PDO::MYSQL_ATTR_INIT_COMMAND set with $db['default']['stricton'] and PDO::MYSQL_ATTR_COMPRESS set with $db['default']['compress']) are not affected by this.

If you want to dig deeper or check which options are set, you can log $this->options in db_connect function in system/database/drivers/pdo/pdo_driver.php and also check database/drivers/pdo/subdrivers/pdo_mysql_driver.php.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.