Codeigniter Database Reference
Other any framework, we need to interaction with the database very oftentimes and CodeIgniter make and use this work easy for us. It provides rich collection of functionalities to interaction with database. In this section,
We'll understand how the CRUD (Create, Read, Update, Delete) functions work and use with CodeIgniter. We'll use a table stack_user and your choice use any table name to select, update, delete, and insert the data stack_user and you use your table name
|Table Name stack_user|
We'll create a database like test name and then run SQL query otherwise manual create a table.
.SQL: CREATE TABLE `test`.`stack_user` ( `user_roll_no` INT NOT NULL AUTO_INCREMENT , `user_name` VARCHAR(50) NOT NULL , PRIMARY KEY (`user_roll_no`)) ENGINE = InnoDB;
Connecting to a Database
We can connect and use to database in the following two step ?
Step-1 Automatic Connecting ? Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every class and page. We just need to add the database library as shown below ?
$autoload['libraries'] = array(‘database’);
Step-2 Manual Connecting ? If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
Insert a Data
Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:
$data = array('user_roll_no'=>'120120','user_name'=>'Rony Azad'); $this->db->insert(‘stack_user’, $data);
// produces a query: INSERT INTO stack_user’ (user_roll_no,user_name) VALUES ('120120', ‘Rony Azad')
The first parameter will contain the table name,"stack_user" the second is an associative array of values .