How to connect to postgresql in codeigniter?

by cali_green , in category: PHP CMS , 2 months ago

How to connect to postgresql in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 2 months ago

@cali_green 

To connect to a PostgreSQL database in CodeIgniter, you need to follow the steps below:

  1. Make sure you have the PostgreSQL driver enabled in your CodeIgniter configuration. To do this, open the application/config/database.php file and make sure that the PostgreSQL driver is set as the default database driver:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'your_postgresql_username',
    'password' => 'your_postgresql_password',
    'database' => 'your_postgresql_database_name',
    'dbdriver' => 'postgre',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);


  1. Next, you need to load the database library in your controller or model where you want to access the database. You can do this by using the following code:
1
$this->load->database();


  1. Once you have loaded the database library, you can use CodeIgniter's active record class to query the database. Here is an example of how you can retrieve data from a table in your PostgreSQL database:
1
2
$query = $this->db->get('table_name');
$result = $query->result();


  1. You can also execute custom SQL queries using CodeIgniter's query method. Here is an example:
1
2
$query = $this->db->query('SELECT * FROM table_name');
$result = $query->result();


That's it! You have now successfully connected to a PostgreSQL database in CodeIgniter. You can now use CodeIgniter's active record class or execute custom SQL queries to interact with your database.