About Me

My photo
im Jaded..i create this blog to share my little knowledge about what i've been taken from my college life and my greatest frustration in life is to develop my own accounting software..

Wednesday, February 13, 2013

How to insert data in to mysql using php with codeigniter

Hello everyone i want to share this little things that i have learn from my friend tutorial and this call "How to insert data in to mysql database with form using code igniter. Assuming you have done all set up and configuration, here is a simple code.



 This our Controller "movie.php"
<?php
class cinema extends CI_Controller{
   
    function construct(){
      parent::__construct();
     }
        function main(){
        $this->load->view('cinema_view');
    }
   
    function showing(){
         $this->load->model('cinema_model');
        $this->cinema_model->postmovies();
       
    }
}

Under controller (above code) first we construct the class(cinema), then we make a method or function to call the view which is the function main() {$this->load->view('cinema_view');} and this is our form(cinema_view) that dispaly when we run this program.

Next we make also a method or function to call the model which is the function showing()
$this->load->model('cinema_model');  // this ('cinema_model') it is your cinema_model.php
$this->cinema_model->postmovies();  // this postmovies() it is your function from model (see below).



<?php



This our Model "cinema_model.php"

class cinema_model extends CI_Model{
   
    function postmovies(){
       
        $Title=$_POST['title'];
        $Genre=$_POST['genre'];
               
        $order = "insert into showing (title,genre) values ('$Title','$Genre')";
       
        $this->db->query($order);
                   
        ECHO "CORRECT?";
    }
   
}

Under model (code above) we make a function which is function postmovies() holds all action here..
Let us explain step by step.
 $Title=$_POST['title'];

// $Title - is the variable
// $_POST - is the method or action saying post this ['title'];
 //['title'] - this is what user input from the form


$order = "insert into showing (title,genre) values ('$Title','$Genre')";

//$order - variable hold the data to be insert
//"insert into showing - command in mysql saying put this data to table showing

//(title,genre) - this is from database column where you want to insert
//values ('$Title','$Genre')"; - this is the variable above holds the data input by the user ['title'];       

//$this->db->query($order); - load to the database

This our form "cinema_view.php"
<html>
<body>
    <form action="<?php echo base_url().'/index.php/cinema/'?>showing" method="post">
    Title<input type="text" name="title"/><br/>
    Genre<input type="text" name="genre"/><br/>
      
    </form>
</body>
</html>

Here in cinema_view.php, which is our form and first line represent our URL, also take action when click the SAVE button,