Friday 22 March 2019

Insert record in Database

This post will help you to learn the basics of inserting the record in the database using ci framework.

Table Structure

Culumn_Name
Data_type
Id
Auto number(int)
Name
Varchar(50)
Email
Varchar(50)
Phone
Varchar(15)
Msg
Varchar(255)


Configure Database

Goto App (Application in older CI) folder then open Config folder then Database.php file change db parameter as per your configuration. 

Database.php 


$db['default'] = array(
       'dsn' 
=> '',
       'hostname' 
=> 'localhost',
       'username' 
=> 'username',
       'password' 
=> 'password',
       'database' 
=> 'db_name',
       'dbdriver' 
=> 'mysqli',
       '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
);


Controller



Public function 
contact()
       {
       $this
->load->view('contact');
       }



public function 
SaveContact()
       {
       $this
->load->database();
       $data 
= array(
              'name' 
=> $_POST['name'],
              'email' 
=> $_POST['email'],
              'phone' 
=> $_POST['phone'],
              'msg' 
=> $_POST['msg']
       );
       if (
$this->db-insert("stu"$data))
 return "<span style=\"color:white\">Thanks for contact us our representative will call you very soon</span>";
         
else
 return "<span style='color:red'>Error Occured</span>";
       }

View


$msg "";

if (isset(
$_POST['submit']))
{
       $CI 
= & get_instance();
       $msg 
$CI->SaveContact();
}

<form method="post">
 <input type="text" placeholder="* Name" name="name">
 <input type="email" placeholder="* Email" name="email">
<input type="text" placeholder="* Phone" name="phone">
<textarea rows="5" placeholder="* Your message" name="msg"></textarea>
<input type="submit" name="submit" value="Submit" > <br>
 <?php echo $msg;?>
</form>

No comments:

Post a Comment