I have created an employee controller for inserting data into database and I would like to set validation before inserting data into the database.
I have tried following way but every time it shows message field is required even though I have filled values in text box.
1) Controller
<?php
class Employee_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
/* Load form validation library */
$this->load->library('form_validation');
$this->load->library('email');
$this->load->library('session');
$this->load->helper('form');
$this->load->database();
}
function add_employee(){
$this->load->view('Employee_add');
}
function insert_emp(){
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Employee_add');
} else {
$this->load->model('Employee_model');
$inserData = array(
'name' =>$_POST['emp_name'],
'salary' => $_POST['emp_salary']
);
$this->Employee_model->insert_employee($inserData);
$emp_list['emp_records']= $this->Employee_model->list_employee();
$this->load->view('Employee_list',$emp_list);
}
}
}
2) Model code ( following is my model code )
<?php
class Employee_model extends CI_Model {
function __construct() {
parent::__construct();
}
function insert_employee($inserData){
$this->db->insert('employee',$inserData);
return true;
}
}
?>
3) View
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="center">
<form action="<?php echo site_url('Employee_controller/insert_emp');?>" method="post">
<?php echo validation_errors(); ?>
<div class="element">
<label>Name</label>
<input type="text" name="emp_name" value="">
</div>
<div class="element">
<label>Salary</label>
<input type="text" name="emp_salary" value="">
</div>
<input type="submit" name="submit" value="Add Employee">
</form>
</div>
</body>
</html>
</body>
</html>
Check your $this->form_validation->set_rules method, you are passing name when your fields are emp_name and emp_salary
Related
I've been trying to get this to work since this morning, but have no idea why it doesn't. The uploaded image gets stored in the database, but when I check my upload folder --where I want to store the images -- there's nothing there.
Can anyone help me with this problem?
Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
//load database libray manually
$this->load->database();
//load Model
$this->load->model('Contact_model');
// load form and url helpers
$this->load->helper(array('form', 'url'));
// load form_validation library
$this->load->library('form_validation');
}
public function Latest_news()
{
$this->form_validation->set_rules('first_content', 'First content', 'required');
$this->form_validation->set_rules('second_content', 'Second content', 'required');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (($this->form_validation->run() == FALSE )&&(!$this->upload->do_upload('filename')))
{
$this->load->view('Latest_news');
}
else
{
//insert
$data = array();
$data['first_content']=$this->input->post('first_content');
$data['second_content']=$this->input->post('second_content');
$data['filename']=$this->input->post('filename');
//Transfering data to Model
$this->Contact_model->latest_news($data);
//Redirecting to success page
redirect(site_url('Home/Latest_news'));
}
}
?>
Contact_model.php
<?php
class Contact_model extends CI_Model
{
function latest_news($data)
{
//saving records
$this->db->insert('latest_news', $data);
}
}
?>
Latest_news.php
<?php echo form_open(); ?>
<div style="padding-top:10%; padding-left:30%">
<div>
<textarea name="first_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("first_content");?></span>
</div><br>
<div>
<textarea name="second_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("second_content");?></span>
</div><br>
<div>
<input type="file" name="filename">
<span><?php echo form_error("filename");?></span>
</div><br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Use function form_open_multipart() in Latest_news.php instead form_open()
controller: Test.php
<?php
class Test extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
$this->Users_model->insert_user();
$this->load->view('home');
}
}
?>
Model: User_model.php
<?php
class Users_model extends CI_Model
{
public function insert_user()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'message' => $this->input->post('message')
);
return $this->db->insert('user', $data);
}
}
?>
view: home.php
<form method="post">
<label for="name">your Name</label>
<input class="form-control" id="name" type="text" placeholder="Name" name="name" />
<label for="email">Your email</label>
<input class="form-control" id="email" type="text" placeholder="Email" name="email" />
<label for="message">Your Message</label>
<textarea class="form-control" id="message" placeholder="Message" name="message"></textarea>
<button type="submit">send</button>
</form>
I am new in codeigniter here I want to insert form value into database but it showing some error i.e.
how can I fix this error ? please help.
Thank You
You got the errors because you call User_model->insert_user() before any data submitted in the form. You should check if there is any posted data then save to the database. Here is the example of your controller should be:
<?php
class Test extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
// do checking right here
if (!empty($this->input->post('name'))) {
$this->Users_model->insert_user();
}
$this->load->view('home');
}
}
You forget to pass POST data in insert method of model in controller .
Contoller
<?php
class Test extends CI_Controller {
public function index()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'message' => $this->input->post('message')
);
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
$this->Users_model->insert_user($data );
$this->load->view('home');
}
}
Model
<?php
class Users_model extends CI_Model
{
public function insert_user($data = [])
{
return $this->db->insert('user', $data);
}
}
?>
You extend CI_Model But did not call parent construct. Use this:
function __construct() {
// Call the Model constructor
parent :: __construct();
}
Hope this will work. Thanks.
In your "home.php" you haven't specify an action attribute. Due to this form value is not posting.
for example:- <form action="<?php echo base_url();?>YourfileName/DeclaredFunctionName" method="post">
and then try to fetch the value of your form in your controller.
In controller please execute this function insert_user() { print_r($_POST); exit(); }
If you are getting values in your browser, then remove exit() and execute your code. Otherwise, please share your error here.
Thanks
I am working with Codeigniter framework these days. I am trying to validate my form data using codeigniter's form_validation library. The problem is I cant get it to work. I dont know where the problem is no error is being shown.
Here is the view page I am calling controller core and function postad in form action
<div class="container table-responsive" id="con1">
<div class="row" id="h4_subad">
<div class="col-md-4"><h4>Submit an Ad</h4></div>
</div>
<form class="form-horizontal" role="form" method="get" action="/core/postad">
<table id="form_table" class="table-responsive table table-striped" id="table_form">
<td>Ad Title*</td><td><input class="form-control" name="ad_title" id="ad_title" type="text" placeholder="Enter Title" id="ad_form"></td>
<tr> <td>Select Category*</td> <td><select name="ad_form" class="form-control" id="ad_form">
<option>Electronics</option>
<option>Mobiles & Accessories</option>
<option>Computers & Accessories</option>
<option>Kitchen Applicances</option>
<option>Clothing</option>
</select></td></tr>
<tr><td>Ad Description*</td><td><textarea name="txt_area" id="txt_area" class="form-control" type="text" placeholder="Enter Description" ></textarea></td></tr>
<tr><td><button type="button" class="btn btn-warning" onclick="core/postad">Submit Ad</button></td></tr>
</table>
</form>
</div>
Controller for this view
class Core extends CI_Controller {
public function index() {
$this->load->view('header1');
$this->load->view('body');
$this->load->view('footer');
}
public function product() {
$this->load->view('header1');
$this->load->view('product');
$this->load->view('footer');
}
public function contact() {
$this->load->view('header1');
$this->load->view('contact');
$this->load->view('footer');
}
public function aboutus() {
$this->load->view('header1');
$this->load->view('aboutus');
$this->load->view('footer');
}
public function reg() {
$this->load->view('header1');
$this->load->view('reg');
$this->load->view('footer');
$this->input->get('username');
}
public function postad() {
$this->load->view('header1');
$this->load->view('postad');
$this->load->view('footer');
$this->load->model('insert_model');
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('txt_area', 'Text Area', 'required|min_length[5]|max_length[15]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('postad');
}
else {
//Setting values for tabel columns
$data = array(
'description' => $this->input->post('txt_area'),
);
//Transfering data to Model
$this->insert_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('insert_view', $data);
}
}
}
Model for database connectivity
<?php
class insert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
$this->db->insert('post_ad', $data);
}
}
?>
Only trying it for just one field txt_area
I dont want to use codeigniter's form helper as I am using bootstrap form.
You should echo the validation_errors(); as below in your html . For more information you can vist this
<?php echo validation_errors(); ?>
<div class="row" id="h4_subad">
<div class="col-md-4"><h4>Submit an Ad</h4></div>
</div>
<form class="form-horizontal" role="form" method="get" action="/core/postad">
<table id="form_table" class="table-responsive table table-striped" id="table_form">
<td>Ad Title*</td><td><input class="form-control" name="ad_title" id="ad_title" type="text" placeholder="Enter Title" id="ad_form"></td>
<tr> <td>Select Category*</td> <td><select name="ad_form" class="form-control" id="ad_form">
<option>Electronics</option>
<option>Mobiles & Accessories</option>
<option>Computers & Accessories</option>
<option>Kitchen Applicances</option>
<option>Clothing</option>
</select></td></tr>
<tr><td>Ad Description*</td><td><textarea name="txt_area" id="txt_area" class="form-control" type="text" placeholder="Enter Description" ></textarea></td></tr>
<tr><td><button type="button" class="btn btn-warning" onclick="core/postad">Submit Ad</button></td></tr>
</table>
</form>
</div>
You need to use validation_errors(); in posted.php file (HTML) for display error message which you validate.
<?php echo validation_errors(); ?>
Form Validation User Manual
Your button to submit the form is incorrect. When you try to submit a form make sure to set the type to submit too.
<button type="submit">Submit form</button>
or
<submit>Submit form</submit>
I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.
Here is the controller, when I click the login button, nothing happens. What I want is to load the success screen when user data is validated and show error messages when user data is not validated.
I have set my base_controller as Login
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function login(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
here is the view
<?php echo validation_errors(); ?>
<form method="post">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
When I click the login button, nothing happens. What am I doing wrong?
You have to give action attribute in form tag, like this:
action="http://yoursitename.com/controllername"
in your case controllername is login.
For more help, you can refer:
[https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html][1]
Hope this help!
this link shows how form_open() works, one of codeigniter's utility functions from the form helper libary.
In your case you would want this line of code:
<?php echo form_open('/login'); ?>
or something that you want to be the login url.
This line would replace
<form method="post">
in your html and when rendered would be something like
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/login" />
If you aren't familiar with URI routing, then you should read about that here](https://ellislab.com/codeigniter/user-guide/general/routing.html). I would recommedn setting up a route for you login, but the default format for a url is
example.com/class/function/id/
so yours might look like
example.com/login/login
And form_open() would then look like (even though its kind of cluncky)
<?php echo form_open('/login/login'); ?>
You can try below code
login.php controller file
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function validate(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
Here I have loaded one helper to give action url in view file
$this->load->helper('url');
Also I have changed function name from login to validate as function name should not be similar to class name as constructor is already defined there
login.php view file
<?php echo validation_errors(); ?>
<form method="post" action = "<?php echo site_url("login/validate"); ?>">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
Hope this will help you