user_guide_src/source/installation/upgrade_database.rst
Upgrade Database ################
.. contents:: :local: :depth: 2
Database Reference Documentation CodeIgniter 3.x <http://codeigniter.com/userguide3/database/index.html>_Working with Databases Documentation CodeIgniter 4.x </database/index>Database Caching <https://www.codeigniter.com/userguide3/database/caching.html>_ functionality known from CI3 was removed.Query Builder <../database/query_builder>
now needs to be initialized before you can run queries on it.Add your database credentials to app/Config/Database.php. The options are pretty much the same as in CI3 only some names have changed slightly.
Everywhere you have used the database you have to replace $this->load->database(); with $db = db_connect();.
If you use multiple databases use the following code to load additional databases $db = db_connect('group_name');.
Now you have to change all database queries. The most important change here is to replace $this->db with just $db and adjust the method name and $db. Here are some examples:
$this->db->query('YOUR QUERY HERE'); to $db->query('YOUR QUERY HERE');$this->db->simple_query('YOUR QUERY') to $db->simpleQuery('YOUR QUERY')$this->db->escape("something") to $db->escape("something");$this->db->affected_rows(); to $db->affectedRows();$query->result(); to $query->getResult();$query->result_array(); to $query->getResultArray();echo $this->db->count_all('my_table'); to echo $db->table('my_table')->countAll();To use the new Query Builder Class you have to initialize the builder $builder = $db->table('mytable'); after that you can run the queries on the $builder. Here are some examples:
$this->db->get() to $builder->get();$this->db->get_where('mytable', array('id' => $id), $limit, $offset); to $builder->getWhere(['id' => $id], $limit, $offset);$this->db->select('title, content, date'); to $builder->select('title, content, date');$this->db->select_max('age'); to $builder->selectMax('age');$this->db->join('comments', 'comments.id = blogs.id'); to $builder->join('comments', 'comments.id = blogs.id');$this->db->having('user_id', 45); to $builder->having('user_id', 45);CI4 does not provide Database Caching <https://www.codeigniter.com/userguide3/database/caching.html>_
layer known from CI3, so if you need to cache the result, use :doc:../libraries/caching instead.
If you use limit(0) in Query Builder, CI4 returns all records in stead of no records due to a bug. But since v4.5.0, you can change the incorrect behavior with a setting. So change the setting. See :ref:v450-query-builder-limit-0-behavior for details.
.. literalinclude:: upgrade_database/ci3sample/001.php
.. literalinclude:: upgrade_database/001.php