In this example I am using a table called news with 3 fields ( id, title, body). If you haven’t already set up your database you will need to do so NOW! Database login details go in config/database.php and I recommend phpmyadmin for management etc.
CREATE TABLE `databaseName`.`blog` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `title` VARCHAR( 100 ) NOT NULL , `body` TEXT NOT NULL ) ENGINE = MYISAM ;
1) Create a new_object function in your controller with appropriate commenting.
/** * @brief New Object Function. * * Calls New Object Form from the Class View folder. * * @see views/blog/new_object.php **/ function new_object() { $this->load->view('blog/new_object'); }
CREATE A CORRESPONDING VIEW WITH A FORM
Before starting this section make sure you have added the form helper to the autoload config file
<?php /** @file views/blog/new_object.php * @brief Create New Object Form. * * @section DESCRIPTION * Simple Create form for new blog posts, requires title * and body fields and calls Blog::insert_object() on submission. **/ ?> <html> <head> <title><?php echo $title; ?></title> </head> <body> <h1><?php echo $heading; ?></h1> <?php echo form_open('blog/insert_object'); ?> <!-- Start a new table --> <table> <!-- For each field create the input fields you require. --> <tbody> <tr> <th>Title:</th> <td><input type="text" name="title" /></td> </tr> <tr> <th>Body:</th> <td><textarea name="body" rows="10"></textarea></td> </tr> <!-- End the table --> </table> <!-- Add a form submit button --> <input type="submit" alt="Save" name="submit" /> <!-- End the form--> </form> </body> </html>
CHECK THE FORM IS OK
You should now be able to view the form using your Browser the following URL:
http://daviesc.big-blue.local/codei/index.php/blog/new_object
INSERT THE RECORD INTO THE DATABASE.
If you create the following function in your Controller you should now be in a position to test your insert routine.
/** * @brief Insert Object Function. * * Inserts a new object into the database and redirects to the index page. * * @todo validate the inputs from the form. **/ function insert_object () { //Set up an array with all your form variables in it. $data = array( 'title' => $this->input->post('title'), 'body' => $this->input->post('body'), ); //Insert record into the database $this->db->insert('blog', $data); //Redirect the page redirect('blog/index'); }
CodeIgniter



