Using multiple controllers cause session error codeigniter - php

When I use only 1 controller in my application, user, everything works fine. When I try to use 2 or 3 to divide the code and create some structure my application always give the following error :
A PHP Error was encountered
Severity: Warning
Message: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/MAMP/htdocs/BT_dashboard/application/controllers/Project.php:99)
Filename: Session/Session.php
Line Number: 140
Backtrace:
File: /Applications/MAMP/htdocs/BT_dashboard/application/controllers/Project.php
Line: 11
Function: __construct
File: /Applications/MAMP/htdocs/BT_dashboard/index.php
Line: 292
Function: require_once
Googled it and tried many things but can't find an answer. I'm using codeigniter 3. My User controller looks like :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* User class.
*
* #extends CI_Controller
*/
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url'));
$this->load->model('user_model');
$this->load->model('employee_model');
$this->load->model('customer_model');
$this->load->model('project_model');
}
public function createProject() {
if ($_SESSION['userlevel']) {
if ($_SESSION['userlevel'] < 3) {
$userid = $this->uri->segment(3);
} else {
$userid = $this->input->post('userproject');
}
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('project_name', 'project name', 'trim|required|min_length[2]|callback_is_project_name_unique[' . $this->input->post('project_name') . ']');
$this->form_validation->set_rules('project_address', 'project address', 'trim|required|min_length[2]');
$this->form_validation->set_rules('project_description', 'project description', 'trim|required|min_length[2]');
$this->form_validation->set_rules('project_city', 'project city', 'trim|required|min_length[2]');
if ($this->form_validation->run() == FALSE) {
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
if ($_SESSION['userlevel'] < 3) {
$this->load->view('dashboard_add_project', $data);
} else {
$data['userslist'] = $this->user_model->get_users_list();
$this->load->view('dashboard_add_project_admin', $data);
}
$this->load->view('wrapper', $data);
} else {
$Address = urlencode($this->input->post('project_address'));
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" . $Address . "&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status == "OK") {
$Lat = $xml->result->geometry->location->lat;
$Lon = $xml->result->geometry->location->lng;
$LatLng = "$Lat,$Lon";
}
//pass validation
$data = array(
'project_name' => $this->input->post('project_name'),
'project_address' => $this->input->post('project_address'),
'project_description' => $this->input->post('project_description'),
'project_city' => $this->input->post('project_city'),
'project_finished' => $this->input->post('project_finished'),
'lat' => $Lat,
'lng' => $Lon,
);
//$this->db->insert('tbl_user', $data);
if ($this->user_model->create_project($data, $userid, $this->input->post('project_name'))) {
if ($_SESSION['userlevel'] > 1) {
$data['projectlist'] = $this->user_model->get_project_list();
$data['uncompleted_projects'] = $this->user_model->get_uncompleted_projects();
$data['completed_projects'] = $this->user_model->get_completed_projects();
} else {
$data['projectlist'] = $this->user_model->get_project_list_userid($userid);
}
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
$this->load->view('dashboard_projects', $data);
$this->load->view('wrapper', $data);
} else {
$data->error = 'There was a problem creating your new employee. Please try again.';
$data['userdata'] = $this->session->userdata;
// send error to the view
$this->load->view('header', $data);
$this->load->view('dashboard_add_project', $data);
$this->load->view('wrapper', $data);
}
}
}
}
My second controller, the project controller. This is the controller I want to use know to paste the createproject code so this gives more structure. But when I paste it here and adapt my views it gives the error. here's my project_controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
* File Name: employee.php
*/
class Project extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url'));
$this->load->model('user_model');
$this->load->model('employee_model');
$this->load->model('customer_model');
}
public function createProject() {
//same as usercontroller
My User/login code in User controller :
public function login() {
$loggedin = $this->session->userdata('logged_in');
if (!$loggedin) {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('user_mail', 'user mail', 'required');
$this->form_validation->set_rules('user_password', 'user password', 'required');
if ($this->form_validation->run() == false) {
$data = new stdClass();
$data->error = 'Check your user and password';
$this->load->view('dashboard_login', $data);
} else {
$usermail = $this->input->post('user_mail');
$password = $this->input->post('user_password');
if ($this->user_model->resolve_user_login($usermail, $password)) {
$user_id = $this->user_model->get_user_id_from_mail($usermail);
$user = $this->user_model->get_user($user_id);
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = (string) $user->user_name;
$_SESSION['logged_in'] = (bool) true;
$_SESSION['user_gsm'] = (string) $user->user_gsm;
$_SESSION['user_address'] = (string) $user->user_address;
$_SESSION['user_city'] = (string) $user->user_city;
$_SESSION['userlevel'] = $this->user_model->get_user_level((int) $user->user_id);
$_SESSION['user_mail'] = $usermail;
$data['userdata'] = $this->session->userdata;
if ($_SESSION['userlevel'] == "3") {
$data['employeetotal'] = $this->user_model->get_amount_employees();
$data['customertotal'] = $this->user_model->get_amount_customers();
$data['projectstotal'] = $this->user_model->get_amount_projects();
}
$this->load->view('header', $data);
$this->load->view('dashboard_index', $data);
$this->load->view('wrapper', $data);
} else {
$data = new stdClass();
// login failed
$data->error = 'Wrong username or password.';
// send error to the view
$this->load->view('dashboard_login', $data);
}
}
} else {
$data['userdata'] = $this->session->userdata;
$data['employeetotal'] = $this->user_model->get_amount_employees();
$data['customertotal'] = $this->user_model->get_amount_customers();
$data['projectstotal'] = $this->user_model->get_amount_projects();
$this->load->view('header', $data);
$this->load->view('dashboard_index', $data);
$this->load->view('wrapper', $data);
}
}
In config/autoload I've got following:
$autoload['libraries'] = array('database','session');

The session library should be automatically loaded for you. There's no reason for you to include it in each of your constructor functions.
Remove it from both controllers, and it'll work fine.
If it does not work, check in your config/autoload.php file to make sure it is being loaded there correctly.

This is a common problem , notice that the error is on line 99 on your controller Project.php (you should have only 76 lines if I am correct). I bet your controller doesn't have 99 lines ... delete the extra lines and the error will vanish.
or if you have an echo on line 99 comment it
hope that helps!

Related

codeigniter : update function model and controller

I don't know what I am doing wrong in this.
If anyone could help!
cause i have tried all solutions...
also undefined variable $data error
/************************/
public function edit_stud($student_id)
{
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
if($this->form_validation->run() === FALSE)
{
$data['student']= $this ->stud_model->update_student($student_id, $data);
$this->load->view('edit_form' , $data);
}
else
{
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name'=>$full_name ,
'father_name'=>$father_name ,
'roll_no'=>$roll_no,
);
$student_id = $this->stud_model->update_student($student_id,$data);
redirect('/stud/edit_stud/'.student_id);
}
}
//***********************Model in CI***//////////////
public function update_student($student_id,$data)
{
$this->db->set($this->table_name,$student_id, $data);
return $this->db->update_id();
}
$data is never defined in the first part of your IF statement.
In particular this line
$data['student'] = $this->stud_model->update_student($student_id, $data);
is the problem. If the form validation is false, you don't want to update the student. Remove that line, and everything should be fine.
Unless you do want to update student even if the validation fails (This is a bad idea, IMO). Then your controller would look like this
public function edit_stud($student_id) {
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name' => $full_name ,
'father_name' => $father_name ,
'roll_no' => $roll_no,
);
$student_id = $this->stud_model->update_student($student_id, $data);
if($this->form_validation->run() === FALSE)
$this->load->view('edit_form' , $data);
} else {
redirect('/stud/edit_stud/'.student_id);
}
}
Thanks for suggestions i have solved the problem i was having
in my code i did some renditions...posting the correct answer for
anyone else, having same sort of problem.
this is the controller code.
/*****controller code*****/
/***************************edit student ******************************/
public function edit_stud($student_id)
{
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
if($this->form_validation->run() === FALSE)
{
$data['student']= $this ->stud_model->get_student($student_id);
$this->load->view('edit_form' , $data);
}
else
{
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name'=>$full_name ,
'father_name'=>$father_name ,
'roll_no'=>$roll_no,
);
$student_id = $this->stud_model->update_student($student_id,$data);
redirect('/stud/edit_stud/'.student_id);
}
}
/************************delete student ************************/
public function delete_stud($student_id)
{
$this ->stud_model->delete_student($student_id);
redirect('/stud/');
}
/***********************model code *******/
/************to get student id*********/
public function get_student($student_id)
{
$this->db->select('*');
$this->db->from($this->table_name);
$this->db->where('id',$student_id);
$query = $this->db->get();
if($query->num_rows() >0)
{
$return = $query->row();
}
else
{
$return = 0;
}
$query->free_result();
return $return;
}
/*****************update function***********************/
public function update_student($id, $data)
{
$where = array('id' => $id);
$this->db->update($this->table_name, $data, $where);
}

Encountering a php error when trying to view my messages with delete button on screen

Instead of my messages appearing on the screen I just see this:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
This is despite my foreach loop in my view page looking ok:
foreach($messages as $message):// this is the line causing the error
$delete = $message['message_id']; // i've even tried removing this line to no avail
//var_dump($message); ?>
<li><?=$message['from']?> says...: "<?=$message['message']?>"(<?=anchor("home/deleteMsg/$delete", 'delete')?>)</li>
<?php endforeach?>
Here is my model:
class Messages extends CI_Model
{
function Messages()
{
parent::__construct();
}
function deleteMsg($message_id) // this message_id is the id field for each message in my database
{
$record = array('message_id' => $message_id);
$this->db->delete('messages', $record);
}
function addMessage($message_id, $from, $to, $message)//this fields come after the message_id field in the database
{
$record = array(
'to' => $to,
'from' => $from,
'message' => $message);
$this->db->insert('messages', $record);
}
function getMessages($user)
{
$this->db->select('*');
$this->db->from('messages');
$this->db->where('to', $user);
$messagesSet = $this->db->get();
$messages = array ();
foreach ($messagesSet->result() as $row)
{
$messages[] = array(
'from' => $row ->from,
'message' => $row ->message);
}
return $messages;
}
}
Here is my controller:
class Home extends CI_Controller
{
function Home()
{
parent::__construct();
$this->load->model('messages');
$this->load->model('friends');
$this->load->model("profiles");
}
function drop($member)
{
$username = $this->session->userdata('username');
$this->friends->deleteFriend($username, $member);
redirect('home');
}
function deleteMsg($messageid) {
$this->messages->deleteMsg($messageid);
redirect('home');
}
function index()
{
$username = $this->session->userdata('username');
$membername = $this->session->userdata('membername');
$viewData['membername'] = $membername;
$viewData['username'] = $username;
$viewData['following'] = $this->friends->getFollowing($username);
$viewData['followers'] = $this->friends->getFollowers($username);
$viewData['messages'] = $this->messages->getMessages($membername);
$viewData['friends'] = $this->friends->getFriends($username);
$viewData['messages'] = $this->messages->deleteMsg($membername);
$this->load->view('shared/header');
$this->load->view('home/hometitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('home/homeview', $viewData);
$this->load->view('shared/footer');
}
}
Your $messages is empty because it's overwritted with this:
$viewData['messages'] = $this->messages->deleteMsg($membername);
in the index function.
Your messages may be empty
<?php
if(!empty($messages)){
foreach($messages as $message):// this is the line causing the error
$delete = $message['message_id']; // i've even tried removing this line to no avail
//var_dump($message); ?>
<li><?=$message['from']?> says...: "<?=$message['message']?>"(<?=anchor("home/deleteMsg/$delete", 'delete')?>)</li>
<?php endforeach?>
<?php }else{ ?>
<?php echo 'Its empty !!!'; }?>

Message Library , My_Controller and __remap issue

I am creating an application and handling common things in MY_Controller. I am using Message library to display common messages.
Here is MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $view = TRUE;
public $theme = FALSE;
public $layout = 'default';
protected $redirect;
protected $models = array();
protected $controller_model;
protected $controller_class;
protected $controller_library;
protected $controller_name;
protected $partials = array(
'meta' => 'partials/meta',
'header' => 'partials/header',
'navigation' => 'partials/navigation',
'content' => 'partials/content',
'footer' => 'partials/footer'
);
public function __construct()
{
parent::__construct();
$this->output->enable_profiler(true);
$this->load->helper('inflector');
$this->load->helper('url');
$this->controller_class = $this->router->class;
if(count($this->models)>0)
{
foreach ($this->models as $model)
{
if (file_exists(APPPATH . 'models/' . $model . '.php'))
{
$this->controller_model = $model;
$this->load->model($model);
}
}
}else{
if (file_exists(APPPATH . 'models/' . $this->controller_model . '.php'))
{
$this->load->model($this->controller_model);
}
}
$this->controller_name = $this->router->fetch_class();
$this->action_name = $this->router->fetch_method();
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$this->run_filter('before', $parameters);
$return = call_user_func_array(array($this, $method),$parameters);
$this->run_filter('after', $parameters);
}else{
show_404();
}
if($this->theme === TRUE OR $this->theme === '')
{
$this->theme = 'default';
$this->template->set_theme($this->theme);
}else if(strlen($this->theme) > 0){
$this->template->set_theme($this->theme);
}else{
}
if($this->layout === TRUE OR $this->layout === '')
{
$this->layout = 'default';
$this->template->set_layout($this->layout);
}else if(strlen($this->layout) > 0){
$this->template->set_layout($this->layout);
}else{
}
if(isset($this->partials))
{
foreach($this->partials as $key => $value)
{
$this->template->set_partial($key,$value);
}
}
if(isset($this->data) AND count($this->data)>0)
{
foreach($this->data as $key => $value)
{
if(!is_object($value))
{
$this->template->set($key,$value);
}
}
}
if($this->view === TRUE OR $this->view === '')
{
if($this->parse == TRUE)
{
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$this->_call_content($this->router->method);
$this->template->build($this->router->method,array());
}
}else if(strlen($this->view) > 0){
if($this->parse == TRUE){
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$view = $this->view;
$this->_call_content($view);
$this->template->build($view,array());
}
}else{
$checkpoint = $this->session->flashdata('exit');
if($checkpoint){
exit();
}else{
$this->session->set_flashdata('exit',TRUE);
}
$this->redirect();
}
}
public function _call_content($view)
{
$value = $this->load->view($view,$this->data,TRUE);
$this->template->set('content',$value);
}
/* Common Controller Functions */
public function index()
{
$data[$this->controller_model] = $this->{$this->controller_model}->get_all();
$this->data = $data;
$this->view = TRUE;
if($this->input->is_ajax_request() || $this->session->flashdata('ajax')){
$this->layout = FALSE;
}else{
$this->layout = TRUE;
}
}
public function form()
{
if($this->input->is_ajax_request() OR !$this->input->is_ajax_request())
{
$this->load->helper('inflector');
$id = $this->uri->segment(4,0);
if($data = $this->input->post()){
$result = $this->{$this->controller_model}->validate($data);
if($result){
if($id > 0){
}else{
$this->{$this->controller_model}->insert($data);
}
$this->message->set('message','The page has been added successfully.');
$this->view = FALSE;
$this->layout = FALSE;
$this->redirect = "index";
}else{
$this->message->set('message','The Red fields are required');
}
}
$row = $this->{$this->controller_model}->where($id)->get();
$this->data[$module_name]= $row;
}
}
public function delete()
{
$id = $this->uri->segment(3,0);
if($id != 0){
$this->{$this->controller_model}->delete($id);
}
$this->view = FALSE;
$this->layout = FALSE;
}
public function redirect()
{
redirect($this->redirect);
}
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
public function query()
{
echo $this->db->last_query();
}
public function go($data = '')
{
if(isset($data)){
echo '<pre>';
print_r($data);
}else{
echo '<pre>';
print_r($this->data);
}
}
}
/**/
As you can see i am using Phil Sturgeon's template library and i am handling the layout with Jamierumbelow's techniques.
When i set a message on form insertion failure its fine. I can display it in the _remap like this
echo $this->message->display();
In the controller its working finebut when i call it in the partial navigation it does not display the message. What can possibly be the problem. I have tried on the different places in the My_Controller. Its working fine but not in the partial or even i have tried it in the failed form i am loading again.
This is the message library i am using
https://github.com/jeroenvdgulik/codeigniter-message
Here i s my navigation partial
<nav>
<div id = "navigation">
<ul id="menubar">
<li>Home</li>
<li>Downloads</li>
<li>About Us</li>
</ul>
</div>
<div id="breadcrumb">
<div class="breadcrumbs">
<!-- Here i will pull breadcrumbs dynamically-->
</div>
<!--<h3>Dashboard</h3>-->
</div>
<br clear = "all"/>
<div id="message">
<?php
$data['message'] = $message ;
$this->load->view('messages/success',$data);?>
</div>
</nav>
The message library is using session might be flashdata so i think its loosing session data somehow. Although i am using sessions correctly autoloading it.
I have found the issue. It was very simple. I was using the base url in config file as empty
$config['base_url'] = '';
I have to change it like this
$config['base_url'] = 'http://localhost/myproject/';

Form validation error-Call to undefined method CI_Form_validation::set_fields() in php codeigniter

When i try to update the query in php- codeigniter I get this form_validation error. Here is my Controller
THIS gives me error and I am not able to update or add an entry into my database
<?php
class Person extends CI_Controller {
// num of records per page
private $limit = 15;
function Person() {
parent::__construct();
//$this->load->library('table','form_validation');
$this->load->library('table');
$this->load->library('form_validation');
$this->form_validation->set_rules();
$this->load->helper('url');
$this->load->model('personModel', '', TRUE);
}
function index($offset = 0) {
$uri_segment = 3;
$offset = $this->uri->segment($uri_segment);
// load data
$persons = $this->personModel->get_paged_list($this->limit, $offset)->result();
// have pagntn
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->personModel->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('No', 'Name', 'Gender', 'Education',
'Date of Birth (dd-mm- yyyy)', 'Interest', 'Actions');
$i = 0 + $offset;
foreach ($persons as $person) {
$this->table->add_row(++$i, $person->name, strtoupper($person->gender) ==
'M' ? 'Male' : 'Female', ($person->education),
date('d-m-Y', strtotime($person->dob)), ($person->interest),
anchor('person/view/' . $person->id, 'view', array('class' => 'view',
'onclick' => "return confirm('View Full Details?')")) . ' ' .
anchor('person/update/' . $person->id, 'update', array('class' => 'update')) . ' ' .
anchor('person/delete/' . $person->id, 'delete', array('class' =>
'delete', 'onclick' => "return confirm('Are you sure want to delete this person?')"))
);
}
$data['table'] = $this->table->generate();
$this->load->library('table');
$this->load->library('form_validation');
// load view
$this->load->view('personList', $data);
}
function add() {
// set validation propert/ies
$this->set_fields();
// set common properties
$data['title'] = 'Add new person';
$data['message'] = '';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function addPerson() {
// set common properties
$data['title'] = 'Add new person';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
$id = $this->personModel->save($person);
// set form input name="id"
$this->form_validation->id = $id;
// set user message
$data['message'] = '<div class="success">add new person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function view($id) {
// set common properties
$data['title'] = 'Person Details';
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// get person details
$data['person'] = $this->personModel->get_by_id($id)->row();
// load view
$this->load->view('personView', $data);
}
function update($id) {
// set validation properties
$this->set_fields();
// prefill form values
$person = $this->personModel->get_by_id($id)->row();
$this->form_validation->id = $id;
$this->form_validation->name = $person->name;
$_POST['gender'] = strtoupper($person->gender);
$this->form_validation->dob = date('d-m-Y', strtotime($person->dob));
// set common properties
$data['title'] = 'Update person';
$data['message'] = '';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function updatePerson() {
// set common properties
$data['title'] = 'Update person';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$id = $this->input->post('id');
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))),
'education'=>$this->input->post('education'),
'interest'=>$this->input->post('interest'));
$this->personModel->update($id, $person);
// set user message
$data['message'] = '<div class="success">update person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function delete($id) {
// delete person
$this->personModel->delete($id);
// redirect to person list page
redirect('person/index/', 'refresh');
}
// validation fields
function set_fields() {
$fields['id'] = 'id';
$fields['name'] = 'name';
$fields['gender'] = 'gender';
$fields['dob'] = 'dob';
$fields['education']='educaiton';
$fields['interest']='
$this->form_validation->set_fields('$fields');
//echo"hellofff";
//exit;
}
// validation rules
function set_rules() {
$rules['name'] = 'trim|required';
$rules['gender'] = 'trim|required';
$rules['dob'] = 'trim|required|callback_valid_date';
$rules['education']='trim|required';
$rules['interest']='trim|required';
$this->form_validation->set_rules($rules);
$this->form_validation->set_message('required', '* required');
$this->form_validation->set_message('isset', '* required');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
}
function form_validation() {
$this->add();
}
// date_validation callback
function valid_date($str) {
if (!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str)) {
$this->form_validation->set_message('valid_date', 'date format is not
valid. dd-mm-yyyy');
return false;
} else {
return true;
}
}
}
?>
This is my model:
PersonMOdel: Database name is employeeregistration and tableused is tbl_person
<?php
class PersonModel extends CI_Model {
// table name
private $tbl_person= 'tbl_person';
function Person(){
parent::construct();
}
// get number of persons in database
function count_all(){
return $this->db->count_all($this->tbl_person);
}
// get persons with paging
function get_paged_list($limit = 15, $offset = 0){
$this->db->order_by('id','asc');
return $this->db->get($this->tbl_person, $limit, $offset);
}
// get person by id
function get_by_id($id){
$this->db->where('id', $id);
return $this->db->get($this->tbl_person);
}
// add new person
function save($person){
$this->db->insert($this->tbl_person, $person);
return $this->db->insert_id();
}
// update person by id
function update($id, $person){
$this->db->where('id', $id);
$this->db->update($this->tbl_person, $person);
}
// delete person by id
function delete($id){
$this->db->where('id', $id);
$this->db->delete($this->tbl_person);
}
}
?>
This can be cossidered a CRUD application.

Very Strange Input issue

I have got a very strange input issue in which it seems that my seo description box and main content box are linked due to if I input any data into the seo input box it changes in the database in the content area as well but not the otherway around.
View:
<?php
//Setting form attributes
$formpageEdit = array('id' => 'pageEdit', 'name' => 'pageEdit');
$formInputTitle = array('id' => 'title', 'name' => 'title');
$formSEODescription = array('id' =>'seoDescription', 'name' => 'seoDescription');
$formTextareaContent = array('id' => 'textContent', 'name' => 'textContent');
?>
<?php print_r($page);?>
<div id ="formLayout" class="editPage">
<?php echo form_open('admin/editpage/index/'.$page[0]['id'].'/'.url_title($page[0]['name'],'dash', TRUE),$formpageEdit); ?>
<?php echo form_fieldset(); ?>
<h4>You are editing: <?= $page[0]['name']; ?> </h4>
<section id = "validation"><?php echo validation_errors();?></section>
<?php
if($success == TRUE) {
echo '<section id = "validation">Page Updated</section>';
}
?>
<label><?php echo form_label ('SEO Description:', 'description');?><span class="small">Required Field</span></label>
<?php echo form_input($formSEODescription, $page[0]['description']); ?>
<label><?php echo form_label ('Content:', 'content');?><span class="small">Required Field</span></label>
<?php echo form_textarea($formTextareaContent, $page[0]['content']); ?>
<script type="text/javascript">CKEDITOR.replace('textContent');</script>
<?php echo form_submit('submit','Submit'); ?>
<?php echo form_fieldset_close();
echo form_close(); ?>
</div>
Model
<?php
/**
* This model handles the sql for the checking of the username in the database
*/
class Page_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function Page_model(){
parent::Model();
}
function getCMSContent($id = NULL) {
$this->db->where('id', $id);
$query = $this->db->get('pages', 1);
if($query->num_rows() > 0) {
$row = $query->result_array();
return $row;
}else{
return FALSE;
}
}
function updatePage($id = NULL, $data = NULL){
#set the $data passed to the function into an array, content being the column name.
$data = array('content' => $data, 'description' => $data);
$this ->db->where('id',$id);
$this->db->update('pages', $data);
return TRUE;
}
}
?>
Controller
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Editpage extends CI_Controller {
function __construct(){
parent::__construct();
}
function index($id){
if(!$this->session->userdata('logged_in'))redirect('admin/home');
if ($this->input->post('submit')){
#The User has submitted updates, lets begin!
#Set The validation Rules
$this->form_validation->set_rules('textContent', 'Content', 'trim|required|xss_clean');
$this->form_validation->set_rules('seoDescription', 'SEO Description', 'trim|required|xss_clean');
#if the form_validation rules fail then load the login page with the errors. Otherwise continue validating the user/pass
if ($this->form_validation->run() == FALSE){
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
#connect to getCMSCotent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['sales_pages'] = $this->sales_model->getSalesPages();
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}
#Form Validation passed, so lets continue updating.
#lets set some variables.
$content = $this->input->post('textContent', TRUE);
$content = $this->input->post('seoDescription', TRUE);
$this->db->escape($content);
#Now if updatePage fails to update hte database then show "there was a problem", you could echo the db error itself
if($this->page_model->updatePage($id, $content)) {
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
#connect to getCMSContent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['success'] = TRUE;
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}//END if updatePage
}else{
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
$data['sales_pages'] = $this->sales_model->getSalesPages();
#connect to getCMSCotent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}//END if post submitted
} //END function index()
}
Found it:
$content = $this->input->post('textContent', TRUE);
$content = $this->input->post('seoDescription', TRUE);
[update below]
You are overwriting the $content variable with the content of seoDescription so textContent never reaches your db.
You need to update your updatePage function:
function updatePage($id = NULL, $content = NULL, $description = NULL){
#set the $data passed to the function into an array, content being the column name.
$data = array('content' => $content, 'description' => $description);
$this ->db->where('id',$id);
$this->db->update('pages', $data);
return TRUE;
}
and call it appropriately:
[...]
#Form Validation passed, so lets continue updating.
#lets set some variables.
$content = $this->input->post('textContent', TRUE);
$description = $this->input->post('seoDescription', TRUE);
$this->db->escape($content);
$this->db->escape($description);
#Now if updatePage fails to update hte database then show "there was a problem", you could echo the db error itself
if($this->page_model->updatePage($id, $content, $description)) {
[...]
By the way are you sure you are using db->escape correctly? The way you're calling it will only work if the escape function accepts parameters by reference (e.g. using & in front of the parameter name, and setting this value to the escaped value). I'd expect this code to be the correct version, but I don't know your db class so I may be wrong:
$content = $this->db->escape($this->input->post('textContent', TRUE));
$description = $this->db->escape($this->input->post('seoDescription', TRUE));

Categories