How to insert form value in ci? - php

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

Related

Html disappear after using form_error function in codeigniter

I am trying to add the form error messages in my html form. Problem is there in first view. In user function html is disappear from where I start to use form_error(). My Original form design is like this: my original form
but after adding the form_error under the first input: my form error image
Here is my html code
<div class="form-group">
<label for="name"><i class="zmdi zmdi-account material-icons-name"></i></label>
<input type="text" name="username" id="name" placeholder="Your Name" />
<?php echo form_error('username','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
<div class="form-group">
<label for="email"><i class="zmdi zmdi-email"></i></label>
<input type="text" name="email" id="email" placeholder="Your Email"/>
<?php echo form_error('email','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
Here is my controller
<?php
class Register extends CI_Controller
{
public function user()
{
$this->load->view('files/registration/signup');
}
public function login()
{
$this->load->view('files/registration/login');
}
public function description()
{
$this->load->view('files/registration/description');
}
public function registerMe()
{
$this->load->helper('form','url');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|alpha|max_length[15]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('re_pass', 'Confirm Password', 'required|matches[pass]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run()===FALSE) {
$this->load->view('files/registration/signup');
}
else
{
$this->load->model('RegisterUser');
$this->RegisterUser->registerme($_POST);
}
}
}
?>
you need to load the form helper in signup function too. form_error is a function in form_helper. (this is required for other functions with a form view too)
public function user()
{
$this->load->helper('form');
$this->load->view('files/registration/signup');
}
html is disappeared because there was php error. check your error log when this happens or change codeigniter environment to development in index.php

Form validation does not work properly in codeIgniter

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

Refreshing page null record automatically inserting in database

I am using codeigniter MVC pattern . Whenever i am refreshing the page, Null record automatically inserting in database. In database, I set the all column as null except primary key.
Please help me.
View page code(index.php)
<div class="title">
<p><strong>ADD USER</strong></p>
</div>
<?php echo form_open("Welcome/index"); ?>
<input type="text" name="userId" placeholder="USER ID" style="width:500px">
<input type="date" name="date" style="width:500px">
<input type="text" name="firtsname" placeholder="FIRST NAME" style="width:330px">
<input type="text" name="middlename" placeholder="MIDDLE NAME" style="width:330px">
<input type="text" name="lastname" placeholder="LAST NAME" style="width:330px">
<input type="text" name="mobileno" placeholder="ENTER MOBILE NO." style="width:500px">
<input type="text" name="landline" placeholder="LANDLINE No." style="width:500px">
<textarea name="address" placeholder="ENTER ADDRESS"></textarea>
<input type="text" name="city" placeholder="CITY" style="width:500px">
<input type="text" name="locality" placeholder="LOCALITY" style="width:500px">
<input type="text" name="email" placeholder="ENTER EMAIL" style="width:1010px"></br>
<input type="submit" class="submit" name="SUBMIT">
<?php echo form_close(); ?>
</div>
Model page code(model_add_user.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Model_add_user extends CI_Model {
public function __construct() {
parent:: __construct();
$this->load->database();
}
public function add_user() {
$data = array(
'userId' => $this->input->post('userId'),
'date' => $this->input->post('date'),
'firtsname' => $this->input->post('firtsname'),
'middlename' => $this->input->post('middlename'),
'lastname' => $this->input->post('lastname'),
'mobileno' => $this->input->post('mobileno'),
'landline' => $this->input->post('landline'),
'address' => $this->input->post('address'),
'city' => $this->input->post('city'),
'locality' => $this->input->post('locality'),
'email' => $this->input->post('email'),
);
$this->db->insert('add_user', $data);
}
}
?>
Controller page code(Welcome.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
//$this->load->view('welcome_message');
$this->load->view('index');
$this->load->model('model_add_user');
$this->model_add_user->add_user();
}
}
?>
In your controller make the following change :
public function index() {
if ($this->input->post()) {
$this->load->model('model_add_user');
$this->model_add_user->add_user();
}
$this->load->view('index');
}
Path up to controller name directly hit the index function of your controller. Here in your code you load view and call add_user function.So every time you refresh the page your model call and null insert into your database
You need to create a separate function for your insert data
public function index()
{
//$this->load->view('welcome_message');
$this->load->view('index');
}
function add_user()
{
$this->load->model('model_add_user');
$this->model_add_user->add_user();
}
And change form action to
<?php echo form_open("Welcome/add_user"); ?>
After successful insertion.. Just redirect it to... function / controller it will refresh the page and prevent the form submission again.
public function index() {
//$this->load->view('welcome_message');
$this->form_validation->set_rules('field', 'Field', 'trim|required');
if ($this->form_validation->run()) {
$this->load->model('model_add_user');
$this->model_add_user->add_user();
redirect('welcome')
} else {
$this->load->view('index');
}
}

Unidentified Property in Control in my codeigniter framework

I am new to frameworks and trying to send values to database table, I have done it simply but now I am using templates (the famous alemsaeed free AdminLTE) now after setting BASEPATH and giving database connection in database.php,I am still getting errors.
However the code looks fine but I don't know please kindly tell me the reason it's my 2nd week in codeigniter.
MODEL
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mdl extends CI_Model {
function __construct() {
parent::__construct();
}
function form_insert($data){
$data = array(
'name' => $this->input->post('name'),
'fname' => $this->input->post('fname'),
'dob' =>$this->input->post('dob')
);
$this->db->insert('folio', $data);
}
}
?>
Controller
public function index() {
$this->load->helper(array('form','url'));
$this->load->view('myself');
}
public function eid() {
$this->load->helper(array('form','url'));
$this->load->database();
$this->load->model('mdl');
$this->model->form_insert();
$this->load->view('edu');
}
}
?>
View
Note:i have shorted the whole view code because it's a template
For Form Loading the usual
<?php
echo form_open(site_url().'/ctrl/eid/');
$attributes = array('class' => 'sidebar-form');
?>
<label>Enter Your Name</label>
<input type="text" class="form-control" placeholder="YourName" name="name">
<label>Father Name</label>
<input type="text" class="form-control" name="fname" placeholder="father name">
<input type="date" class="form-control" name="dob" placeholder="DD/MM/YYYY" >
<button type="submit" class="btn btn-info pull-right">Submit</button>
</div>
<div class="box-footer">
Copyright © 2015-2016 PIET MULTAN.</strong> All rights reserved.
</div>
</div>
Remove argument $data from form_insert method of model. Like: public function form_insert() {/* rest of code here */} because you are not passing anything from controller. Although I would advice you that you do that passing from controller like:
public function eid()
{
//controller
$data = array();
$data['name'] => $this->input->post('name'),
$data['fname'] => $this->input->post('fname'),
$data['dob'] =>$this->input->post('dob'),
$this->load->helper(array('form','url'));
$this->load->database();
$this->load->model('mdl');
if ( $this->model->form_insert($data) )
{
//success view
}
else
{
//insert fail view
}
}
function form_insert($data)
{
//model
$this->db->insert('folio', $data);
return $this->db->affected_rows() > 0;
}
In Controller
function __construct()
{
parent::__construct();
//load default helpers in this
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('mdl');
}
public function index()
{
$this->load->view('myself');
}
public function eid()
{
$name = $_POST['name'];
$fname = $_POST['fname'];
$dob = $_POST['dob'];
if(!empty($name) || !empty($fname) || !empty($dob))
{
$this->Mdl->form_insert($name, $fname, $dob);//Model name should be Mdl
$this->load->view('edu');
}
else
{
//fields are empty
}
}
In Model
function form_insert($name, $fname, $dob)
{
$data = array(
'name' => $name,
'fname' => $fname,
'dob' => $dob
);
$this->db->insert('folio', $data);
}
In View (Form should be)
<form action="<?php echo base_url();?>index.php/ctrl/eid" method="post" class="sidebar-form">
<label>Enter Your Name</label>
<input type="text" class="form-control" placeholder="YourName" name="name">
<label>Father Name</label>
<input type="text" class="form-control" name="fname" placeholder="father name">
<label>Date Of Birth</label>
<input type="date" class="form-control" name="dob" placeholder="DD/MM/YYYY" >
<button type="submit" class="btn btn-info pull-right">Submit</button>
</form>
The Problem was in the Controller
it should be the modelfileName not model in the code where we load the function
$this->mdl->form_insert();
And this did work :D
The Next problem was in the sitemap
it was this before
$config['site_url']='../../folio/';
instead of this
$config['site_url']='http://localhost/folio/index.php/';
But Once Again i appreciate all for your help it really means to me a lot .
THK_STACOVRFLW

User registration with CodeIgniter

I'm trying to build a registration system with CodeIgniter. I have a controller called Register with the following code:
class Register extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
$this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
$this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
$this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
$this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim');
$this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|trim');
$this->load->view('header');
if(!$this->form_validation->run())
{
$this->load->view('register_form');
}
else
{
$this->load->view('register_done');
}
$this->load->view('footer');
}
}
So far so good. If I go to the register page I get the registration form displayed. If I send the form and it passes the form validation checks, I get the success page, if the form has errors, I get the form back with some error messages.
Now what I want to do is the database stuff. I have some idea of how I can get the POST values from the registration form into my database, but no clue how I can check if a username or email already exists, and if so, display that error on the registration form. Here's my registration form view:
<?php $this->load->helper('form'); ?>
<?php echo form_open('register'); ?>
<ul id="register">
<ul>
<h3>Account information</h3>
<li>
<label for="username">Choose a username</label>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" />
<span class="desc">The name you'd like to be known by</span>
<?php echo form_error('username'); ?>
</li>
<li>
<label for="password">Pick a password</label>
<input type="password" name="password" />
<span class="desc">The best passwords are random and more than 6 characters long</span>
<?php echo form_error('password'); ?>
</li>
<li>
<label for="email">Enter your valid email address</label>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" />
<span class="desc">We'll send you an activation email</span>
<?php echo form_error('email'); ?>
</li>
</ul>
<ul>
<h3>About you</h3>
<li>
<label for="band">Who's your favorite artist?</label>
<input type="text" name="artist" value="<?php echo set_value('artist'); ?>" />
<span class="desc">Don't put Lady GaGa.</span>
<?php echo form_error('artist'); ?>
</li>
</ul>
<ul>
<h3>Security question</h3>
<li>
<label for="captcha">Enter the letters you see in the image</label>
<?php $this->load->helper('captcha');
$cap = create_captcha(array('img_path' => './captcha/', 'img_url' => 'http://localhost/captcha/', 'img_width' => 200, 'img_height' => 30));
$data = array('captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word']);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo $cap['image']; ?>
<input type="text" name="captcha" />
<?php echo form_error('captcha'); ?>
</li>
</ul>
<ul>
<h3 class="submit">
<input type="submit" value="Register" />
</h3>
</ul>
</ul>
<?php echo form_close(); ?>
As you can see, I'm taking advantage of the form_error() function of CI to display form errors right under the field, and I would like the "username already exists" error to also be displayed under the username field.
Can anyone provide some help? Even a nudge in the right direction?
Thanks!
I would strongly urge you to think about using another library that already does this very well: TankAuth. TankAuth is easily modifiable and offers email confirmation, very secure password hashing, a solid database schema, and very clean code.
There's no reason to reinvent the wheel, especially when it comes to something that's very hard to get right like user authentication.
EDIT:
For example, here's everything TankAuth provides security-wise that you'd have to code yourself (if you cared about security) - how much time would that take?
Using phpass library for password hashing (instead of unsafe md5).
Counting login attempt for bruteforce preventing (optional). Failed login attempts determined by IP and by username.
Logging last login IP-address and time (optional).
CAPTCHA for registration and repetitive login attempt (optional).
Unactivated accounts and forgotten password requests auto-expire.
You need to create a model for your controller.
Your model would look like this:
class Register_model extends CI_Model {
function register_user()
{
$data['username'] = $this->input->post('username');
$data['password'] = sha1($this->input->post('password'));
... (your other post data) ...
$this->db->insert('users', $data);
}
}
In your controller you will call the model this way:
$this->load->model('Register_model');
and the method goes here:
else
{
$this->Register_model->register_user();
$this->load->view('register_done');
}
If you want to check if the username is available, you simply put SELECT query on the first lines of the register_user() method (function).
To do the check you should have functions in your model that can look up those types of things for you:
class Model{
function getUserByEmail($email);
function getUserByUsername($username);
...
}
Then in your controller you can call these methods
...
$result = $model->getUserByEmail($_POST['email']); // You'll need to sanitize your POST
if(count($result) > 0){
// Sent error about email already existing and flag to not insert/update user
}
...
The easiest solution in CodeIgniter is to use a callback function as one of the rules in your form validation.
I've used this method myself to check the username and e-mail.
Here's the docs for it.
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
// Load session library
$this->load->library('session');
// Load database
$this->load->model('User_model');
}
public function index()
{
$this->load->view('index');
}
public function project()
{
$this->data['posts'] = $this->User_model->getPosts(); // calling Post model method getPosts()
$this->load->view('tables', $this->data);
// $this->load->aview('project');
}
public function get_project()
{
$this->User_model->get_project($data);
}
public function signin()
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$this->User_model->signin($data);
}
public function logout()
{
$this->session->unset_userdata($_SESSION['email']);
// $this->session->sess_destroy();
redirect('User');
}
public function signup()
{
$data = array(
'name' => $this->input->post('name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
if($this->User_model->signup($data))
{
echo "no insert";
}
else
{
$this->load->view('index', $data);
}
}
}
<?php
Class User_model extends CI_Model {
function __construct() {
parent::__construct();
$this->load->library('session');
}
public function signup($data)
{
$this->db->insert('user_signup',$data);
}
public function getPosts()
{
$this->db->select("*");
$this->db->from('user_data');
$query = $this->db->get();
return $query->result();
}
public function signin($data)
{
$this->db->where('email',$data['email']);
$this->db->where('password',$data['password']);
$query=$this->db->get('user_signup');
if($query->num_rows()==1){
$_SESSION['email'] = $data['email'];
$this->load->view('popup',$data);
return true;
}
else{
echo "no";
return false;
}
}
}

Categories