Hi, sometime back I wrote a tutorial on codeigniter contact form with email sending option. It received good response and I got requests from blog readers to write about saving the codeigniter contact form data into database. For doing so, it requires a proper database to store the form data and some tweaking to the script. Though it’s easy for experienced developers, it’s proves to be a challenge for newbie’s to do it by themselves. So I decided to write a detailed tutorial here about creating simple contact form in codeigniter and saving the data into database.
Recommended Read: CodeIgniter Basic CRUD Operations using MySQL
Contact Form Workflow
The workflow of the codeigniter contact form we build goes like this. Create a simple contact form for the user to enter ‘name’, ‘email-id’, ‘subject’ and ‘message’. Upon proper server side validation we should insert the form data into database. If the database insert operation succeeds, we notify the user with some success message else the error message.
Creating CodeIgniter Contact Form and Save in Database
As the foremost step we need to create database with proper fields to store the contact form data. I’m going to use MySQL DB and create a database with name ‘mysite’. Next we should create a table inside the database. For that run this below ‘sql’ file to create the table required to store the contact form data.
Contacts.sql
--
-- Database: `mysite`
--
-- Table structure for table `contacts`
--
CREATE TABLE IF NOT EXISTS `contacts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(60) NOT NULL,
`email` varchar(255) NOT NULL,
`subject` varchar(120) NOT NULL,
`message` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Connect to Database
Next we have to connect the codeigniter app to our ‘mysite’ database. Copy paste the below connectivity settings to ‘application\config\database.php’ file and you are done.
$db['default']['hostname'] = 'localhost'; //server
$db['default']['username'] = 'username'; //mysql username
$db['default']['password'] = 'password'; //mysql password
$db['default']['database'] = 'mysite'; //database name
$db['default']['dbdriver'] = 'mysql';
Note: Change the above db settings according to your needs.
Next we’ll move on to the coding phase. We need to create a controller and a view file for this contact form. For styling the form, I will use twitter bootstrap css in view file (Not mandatory. Feel free to use your own stylesheets). You can learn here to set up the twitter bootstrap css with codeigniter.
The Contact Form Controller File (‘contactform.php’)
Create a controller file with name ‘contactform.php’ inside ‘application\controllers’ folder. Now copy paste the below code to it and save.
<?php
class contactform extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
}
function index()
{
//set validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean|callback_alpha_space_only');
$this->form_validation->set_rules('email', 'Emaid ID', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
$this->form_validation->set_rules('message', 'Message', 'trim|required|xss_clean');
//run validation on post data
if ($this->form_validation->run() == FALSE)
{ //validation fails
$this->load->view('contact_form_view');
}
else
{
//insert the contact form data into database
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'subject' => $this->input->post('subject'),
'message' => $this->input->post('message')
);
if ($this->db->insert('contacts', $data))
{
// success
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">We received your message! Will get back to you shortly!!!</div>');
redirect('contactform/index');
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Some Error. Please try again later!!!</div>');
redirect('contactform/index');
}
}
}
//custom callback to accept only alphabets and space input
function alpha_space_only($str)
{
if (!preg_match("/^[a-zA-Z ]+$/",$str))
{
$this->form_validation->set_message('alpha_space_only', 'The %s field must contain only alphabets and space');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
As you can see in the above controller file, first we have loaded the required files in the constructor function. And the index()
is the default function to be called when the controller is invoked. Here is where we run the validation check on the posted data and if it is valid, we save the contact form data into mysql table ‘contacts’ using the $this->db->insert('contacts', $data);
statement.
The statement $this->session->set_flashdata()
is used to notify success or failure message to the user, and the flashdata message will be displayed when the page is redirected.
We also have a custom callback alpha_space_only()
which is used for validating the name field to allow only alphabets and space characters.
The Contact Form View File (‘contact_form_view.php’)
Next we have to create the view file which we load in the controller. Create a file with name ‘contact_form_view.php’ inside ‘application\views’ folder. Now copy paste the below code to it and save.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter Contact Form Example</title>
<link href="<?php echo base_url("assets/bootstrap/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Contact Form</h3>
</div>
<div class="panel-body">
<?php $attributes = array("name" => "contactform");
echo form_open("contactform/index", $attributes);?>
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" name="name" placeholder="Your Full Name" type="text" value="<?php echo set_value('name'); ?>" />
<span class="text-danger"><?php echo form_error('name'); ?></span>
</div>
<div class="form-group">
<label for="email">Email ID</label>
<input class="form-control" name="email" placeholder="Email-ID" type="text" value="<?php echo set_value('email'); ?>" />
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input class="form-control" name="subject" placeholder="Subject" type="text" value="<?php echo set_value('subject'); ?>" />
<span class="text-danger"><?php echo form_error('subject'); ?></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="message" rows="4" placeholder="Message"><?php echo set_value('message'); ?></textarea>
<span class="text-danger"><?php echo form_error('message'); ?></span>
</div>
<div class="form-group">
<button name="submit" type="submit" class="btn btn-success">Submit</button>
</div>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</div>
</div>
</div>
</body>
</html>
As I have already mentioned about using bootstrap css, we have linked the bootstrap css file in the view to style the user interface. All the css classes used inside the html markup belong to bootstrap framework.
Now run the controller in the browser (http://localhost/cidemo/index.php/contactform) and you can see a neatly aligned contact form like this.
CodeIgniter Contact Form Example |
In case of any validation errors, we repopulate the form data with codeigniter’s set_value()
method and use the form_error()
method to display the error message below the respective form fields like this,
Validation Errors Displayed in Contact Form |
As for notifications, the statement $this->session->flashdata('msg');
is included below the form to display the success or failure message in green or red color respectively.
Success Message Notification |
Failure Message Notification |
And that explains about creating codeigniter contact form and storing the form data into mysql database. I hope this codeigniter contact form tutorial is helpful to you. Feel free to voice your comments if you have any queries.
Also Read: CodeIgniter Contact Form Tutorial with Email Sending Option
Don’t Miss: CodeIgniter Login Form using MySQL and Twitter Bootstrap
Source
BalasHapuswebsite link
click for info
go now
get more