Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter $this->db->reconnect(); usage

I’m not autoloading db because most pages of my application don’t need db processing otherwise whole thing will slow down. What I want to do is not to establish a new connection to db when there is one already alive and use it instead not to bother server-db. So how do I implement $this->db->reconnect(); to my example below? I read user guide but no exact example there.

Note : If I necessary to use $this->db->close(); and $this->db->initialize(); then please help me implement them as well because I heard that calling $this->db->reconnect(); with autoloading disabled will throw an error.

I’m using CI 2.1

Thanks

class Test_model extends CI_Model
{
 public function __construct()
 {
  parent::__construct();

  $this->load->database();
 }

 public function function_a($id)
 {
  $this->db->protect_identifiers('year');

  $sql = "SELECT * FROM year WHERE id = ?";

  $data['dbquery'] = $this->db->query($sql, array($id));

  return $data['dbquery'];
 }

 public function function_b($id)
 {
  $this->db->protect_identifiers('month');

  $sql = "SELECT * FROM month WHERE id = ?";

  $data['dbquery'] = $this->db->query($sql, array($id));

  return $data['dbquery'];
 }


 public function function_c($id)...
 public function function_d($id)...
 public function function_e($id)...
} 
like image 391
BentCoder Avatar asked Dec 16 '22 21:12

BentCoder


2 Answers

Basically if you keep pconnect=false in database.php then the connection will be closed at the end of each script’s execution automatically and by default it set to false.

Well if you want then you can use

$this->db->close();

after every query execution to close the connection manually and use

$this->db->initialize();

before any query execution to initialize the connection again after closing it.

like image 139
The Alpha Avatar answered Dec 26 '22 22:12

The Alpha


The best way to do it is just close the connection and reconnect manually with:

$this->db->close();
$this->db->initialize(); 
like image 41
Abid Hussain Avatar answered Dec 26 '22 21:12

Abid Hussain