Controller I have form_ctrl code is below
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class form_ctrl extends CI_Controller {
public function index()
{
//$this->load->view('welcome_message');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
//$this->form_validation->set_rules('name', 'Username', 'required');
$this->form_validation->set_rules('name', 'name','required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required');
$this->form_validation->set_rules('address', 'Address','required|min_length[5]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('table');
}
else
{
$this->load->view('results');
$name=$this->input->post('name');
$pass=$this->input->post('pass');
$email=$this->input->post('email');
$mobile=$this->input->post('mobile');
$address=$this->input->post('address');
$data = array(
'name' =>$name ,
'pass' => $pass,
'email' => $email,
'mobile' => $mobile,
'address' => $address
);
$this->db->insert('form', $data);
}
}
}
View I have result.php code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open(); ?>
<table >
<tr>
<td colspan=2 align="center"><h3>User Details</h3></td>
</tr>
<tr>
<td>
<?php echo form_label('Name'); ?>
</td>
<td>
<?php echo form_input(array('id' => 'name', 'name' => 'name')); ?>
</td>
</tr>
<tr>
<td>
<?php echo form_label('Pass'); ?>
</td>
<td>
<?php echo form_password(array('id' => 'pass', 'name' => 'pass')); ?>
</td>
</tr>
<tr>
<td><?php echo form_label('Email'); ?>
</td>
<td><?php echo form_input(array('id' => 'email', 'name' => 'email')); ?></td>
</tr>
<tr>
<td><?php echo form_label('Mobile'); ?>
</td>
<td><?php echo form_input(array('id' => 'mobile', 'name' => 'mobile')); ?>
</td>
</tr>
<tr>
<td><?php echo form_label('Address'); ?>
</td>
<td><?php echo form_input(array('id' => 'address', 'name' => 'address')); ?>
</td>
</tr>
<tr>
<td colspan="2" align="center"><?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
</td>
</tr>
<?php echo form_close(); ?>
</table>
</body>
</html>
In this code I want to include model to insert the data instead of controller.
The code is working properly for insert data into database but I want this through model not from controller. I tried so many times but I didn't get the desirable result.
commonModel.php
class CommonModel extends CI_Model {
function __construct() {
parent::__construct ();
}
public function insert($tableName,$data){
return $this->db->insert($tableName, $data);
}
}
replace your controller code like this
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class form_ctrl extends CI_Controller {
public function index()
{
//$this->load->view('welcome_message');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('commonModel');
//$this->form_validation->set_rules('name', 'Username', 'required');
$this->form_validation->set_rules('name', 'name','required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required');
$this->form_validation->set_rules('address', 'Address','required|min_length[5]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('table');
}
else
{
$this->load->view('results');
$name=$this->input->post('name');
$pass=$this->input->post('pass');
$email=$this->input->post('email');
$mobile=$this->input->post('mobile');
$address=$this->input->post('address');
$data = array(
'name' =>$name ,
'pass' => $pass,
'email' => $email,
'mobile' => $mobile,
'address' => $address
);
$this->commonModel->insert('form', $data);
}
}
}
class form_ctrl extends CI_Controller {
public function index()
{
//$this->load->view('welcome_message');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
//$this->form_validation->set_rules('name', 'Username', 'required');
$this->form_validation->set_rules('name', 'name','required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required');
$this->form_validation->set_rules('address', 'Address','required|min_length[5]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('table');
}
else
{
$this->load->view('results');
$name=$this->input->post('name');
$pass=$this->input->post('pass');
$email=$this->input->post('email');
$mobile=$this->input->post('mobile');
$address=$this->input->post('address');
$data = array(
'name' =>$name ,
'pass' => $pass,
'email' => $email,
'mobile' => $mobile,
'address' => $address
);
$this->load->model ( 'user_model' );
$this->user_model->insert('form', $data);
}
}
}
model
class User_model extends CI_Model
{
public function insert($table,$data)
{
$this->db->insert ( $table, $data );
}
}
class form_ctrl extends CI_Controller {
public function index(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name','required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required');
$this->form_validation->set_rules('address', 'Address','required|min_length[5]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('table');
}
else
{
$data = $this->input->post();
$this->load->view('results',$data);
$this->load->model ( 'user_model' );
$this->user_model->insert('form', $this->input->post());
}
}
}
and your model looks like below.
public function insert($table, $data) {
$param = array(
'name' => $data['name'],
'pass' => $data['pass'],
'email' => $data['email'],
'mobile' => $data['mobile'],
'address' => $data['address']
);
$this->db->insert($table, $param);
}
It's always best practices that your controller part will be light weight and have less code.
**controller**
$postData = $_POST;
$result = $this->batch->addBatch($postData);
**Batch Model**
class Batch_model extends MY_Model {
public function __construct() {
parent::__construct();
}
function addBatch($postData) {
$this->_table = TBL_BATCH;
$result = $this->add($postData);
return $result;
}
}
**My Model**
public $_table;
public $_fields;
public $_where;
protected $_except_fields = array();
protected $soft_delete = TRUE;
function add($PostData) {
$postArray = $this->getDatabseFields($PostData);
$query = $this->db->insert($this->_table, $postArray);
if ($this->db->affected_rows() > 0)
return $this->db->insert_id();
else
return '';
}
protected function getDatabseFields($postData, $tableName = '') {
if (empty($tableName))
$tableName = $this->_table;
$table_fields = $this->getFields($tableName);
$final = array_intersect_key($postData, $table_fields);
return $final;
}
Controller I have form_ctrl code is below
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class form_ctrl extends CI_Controller {
public function index()
{
//$this->load->view('welcome_message');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
//$this->form_validation->set_rules('name', 'Username', 'required');
$this->form_validation->set_rules('name', 'name','required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required');
$this->form_validation->set_rules('address', 'Address','required|min_length[5]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('table');
}
else
{
$this->load->view('results');
$name=$this->input->post('name');
$pass=$this->input->post('pass');
$email=$this->input->post('email');
$mobile=$this->input->post('mobile');
$address=$this->input->post('address');
$data = array(
'name' =>$name ,
'pass' => $pass,
'email' => $email,
'mobile' => $mobile,
'address' => $address
);
$this->your_model->insert_data($data)
}
}
}
Here is your model your_model..........
class your_model extends CI_Model
{
function insert_data($data) {
$this->db->insert('your_table', $data);
}
}
** You must load your_model to controller or in autoload
Related
autoload:
$autoload['libraries'] = array('database','form_validation');
controller:
class Adminlogin extends CI_controller
{
public function new_user()
{
$this->form_validation->set_rules('name','name','required');
$this->form_validation->set_rules('email','email','required|valid_email');
$this->form_validation->set_rules('password','password','required|min_length[8]|max_length[15]');
if ($this->form_validation->run())
{
$Name = $this->input->POST('name');
$Email = $this->input->POST('email');
$Password = $this->input->POST('password');
$data = array('Name' => $Name, 'Email' => $Email, 'Password' => $Password);
$this->load->model('login_model');
$this->login_model->newuser_data($data);
//redirect('public/login_form');
$data['message'] = 'Data Inserted Successfully';
}
else
{
echo "not done";
}
}
if I remove condition from validation then form works and data in traveled and when I apply condition on validation then form not working data is also not traveling without showing any error.
model:
public function newuser_data($data)
{
$this->db->insert('users', $data);
$query = $this->db->insert_id();
}
view:
<?php echo form_open('adminlogin/new_user'); ?>
<div class="col-md-4">
<center><h3>Create User!</h3>
<div class="form-group">
<?php echo form_input(['type'=>'name','name'=>'name','placeholder'=>'Name','class'=>'form-control contact-form','value'=>set_value('name')]) ?>
<?php echo form_error('name'); ?>
</div>
<div class="form-group">
<?php echo form_input(['type'=>'email','name'=>'email','placeholder'=>'Email','class'=>'form-control contact-form','value'=>set_value('Email')]) ?>
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<?php echo form_input(['type'=>'Password','name'=>'password','placeholder'=>'Password','class'=>'form-control contact-form','value'=>set_value('Password')]) ?>
<?php echo form_error('password'); ?>
</div>
<div class="form-group text-right button-submit btn-submit">
<?php echo form_submit(['name'=>'submit','value'=>'Login','class'=>'btn btn-primary']) ?>
</div>
</div>
class Adminlogin extends CI_controller
{
public function new_user()
{
$this->form_validation->set_rules('name','name','required');
$this->form_validation->set_rules('email','email','required|valid_email');
$this->form_validation->set_rules('password','password','required|min_length[8]|max_length[15]');
if ($this->form_validation->run()!=FALSE)
{
$Name = $this->input->POST('name');
$Email = $this->input->POST('email');
$Password = $this->input->POST('password');
$data = array('Name' => $Name, 'Email' => $Email, 'Password' => $Password);
$this->load->model('login_model');
$this->login_model->newuser_data($data);
//redirect('public/login_form');
$data['message'] = 'Data Inserted Successfully';
}
else
{
echo "not done";
}
}
Change in if condition
if ($this->form_validation->run())
to
if ($this->form_validation->run()!=FALSE)
change this to
if ($this->form_validation->run())
to
if ($this->form_validation->run() != FALSE)
Read - Form Validation in codeigniter.com
Change your line
if ($this->form_validation->run())
to
if ($this->form_validation->run()===TRUE)
Change your statement
From
if ($this->form_validation->run())
To
if ($this->form_validation->run() == TRUE)
OR
if ($this->form_validation->run() != FALSE)
Try using this controller
class Adminlogin extends CI_controller
{
public function new_user()
{
$this->form_validation->set_rules('name','name','required');
$this->form_validation->set_rules('email','email','required|valid_email');
$this->form_validation->set_rules('password','password','required|min_length[8]|max_length[15]');
if ($this->form_validation->run()===FALSE)
{
echo 'Not done';
}
else
{
$Name = $this->input->POST('name');
$Email = $this->input->POST('email');
$Password = $this->input->POST('password');
$data = array('Name' => $Name, 'Email' => $Email, 'Password' => $Password);
$this->load->model('login_model');
$this->login_model->newuser_data($data);
$data['message'] = 'Data Inserted Successfully';
}
}
I'm sorry to ask again, I already check answered questions about this but I really can't solve this problem. Any help please. Thank you!
Autoload: $autoload['helper'] = array('form', 'url');
View:
<?php
echo form_open('members/update_password_validation/'.$id, array('role' => 'form'));
echo validation_errors();
echo '<div class="form-group">';
echo form_label('Password:', 'password');
echo form_password(array('name' => 'password', 'id' => 'password', 'class' => 'form-control'));
echo '</div>';
echo '<div class="form-group">';
echo form_label('Confirm Password:', 'cpassword');
echo form_password(array('name' => 'cpassword', 'id' => 'cpassword', 'class' => 'form-control'));
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('name' => 'update_password_submit', 'value' => 'Update Password', 'class' => 'btn btn-default'));
echo '</div>';
echo form_close();
?>
Controller:
class Members extends CI_Controller {
public function index()
{
//some code here
}
public function update_password_validation($id)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');
if ($this->form_validation->run())
{
//success
}
else
{
//fail
}
}
}
Why does $this->form_validation->run() always return false?
if ($this->form_validation->run() == FALSE)
{
//success
}
else
{
//fail
}
When I submit my form my controller[] array post does not work throws errors.
Error 1
A PHP Error was encountered Severity: Notice Message: Array to string
conversion Filename: mysqli/mysqli_driver.php Line Number: 544
Error Number: 1054 Unknown column 'Array' in 'field list' INSERT INTO
user_group (name, controller, access, modify) VALUES
('Admin', Array, '1', '1') Filename:
C:\Xampp\htdocs\riwakawebsitedesigns\system\database\DB_driver.php
Line Number: 331
It is not inserting the controller names. Not sure best way to fix?
Model
<?php
class Model_user_group extends CI_Model {
public function addUserGroup($data) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $this->input->post('controller'),
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
?>
Controller
<?php
class Users_group extends Admin_Controller {
public function index() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->input->post('name') !== FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
$ignore = array(
'admin',
'login',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['controllers'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
if (!in_array($controller, $ignore)) {
$data['controllers'][] = $controller;
}
}
if ($this->input->post('name') !== FALSE) {
$data['controller'] = $this->input->post('controller');
} else {
$data['controller'] = $user_group_info['controller'];
}
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'User Group Name', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/user/users_group_form.tpl', $data);
} else {
$this->load->model('admin/user/model_user_group');
$this->model_user_group->addUserGroup($this->input->post());
redirect('admin/users_group');
}
}
}
?>
View
<?php echo validation_errors('<div class="alert alert-warning text-center"><i class="fa fa-exclamation-triangle"></i>
', '</div>'); ?>
<?php if ($this->uri->segment(4) == FALSE) { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/add', $data);?>
<?php } else { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/edit' .'/'. $this->uri->segment(4), $data);?>
<?php } ?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Name', 'name', $data);?>
<div class="col-sm-10">
<?php $data1 = array('id' => 'name', 'name' => 'name', 'class' => 'form-control', 'value' => $name);?>
<?php echo form_input($data1);?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<?php foreach ($controllers as $controller) {?>
<tbody>
<tr>
<td><?php echo $controller;?>
<input type="hidden" name="controller[]" value="<?php echo $controller;?>" />
</td>
<td>
<select name="access" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
<td>
<select name="modify" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<?php echo form_close();?>
The error is because you cannot insert php-array in database.
Instead store comma separated values.
In your model change data array as below:
public function addUserGroup($data) {
$controllers = $this->input->post('controller');
$name = $this->input->post('name');
$access = $this->input->post('access');
$modify = $this->input->post('modify');
for($i=0;$i<count($controllers);$i++) {
$data = array(
'name' => $name,
'controller' => $controllers[$i],
'access' => $access,
'modify' => $modify
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
}
Your controller hidden field is an array. You're passing this array to your addUserGroup function, which is trying to insert this array into the database. It's implicitly trying to convert this array to a string. Maybe try changing your function to this:
'controller' => $this->input->post('controller')[0],
Problem fixed foreach in model Thanks for the ideas on how to fix problems every one.
foreach ($this->input->post('controller') as $controller) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $controller,
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
I have a form for insert pages on the database,the trouble is that I can't detected in form if a URL is duplicated in my database,because I should to configure a callback function.The error is only on the callback function because I can insert,delete and create pages with this form.
This is my Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Create_Pages extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
/*$this->load->library('pagination');*/
$this->load->model('Create_Pages_Model');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['Username'] = $session_data['Username'];
}
else
{
$this->load->view('view_error');
}
}
public function add_new_page()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['Username'] = $session_data['Username'];
$this->load->view('view_admin_content_panel', $data);
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Create_Pages_Model');
$data_pages = array(
'TitlePage' => $this->input->post('TitlePage'),
'SectionPage' => $this->input->post('SectionPage'),
'CategoryPage' => $this->input->post('CategoryPage'),
'NamePage' => $this->input->post('NamePage'),
'DescriptionPage' => $this->input->post('DescriptionPage'),
'BodyPage' => $this->input->post('BodyPage')
);
if($this->input->post())
{
$this->form_validation->set_rules('TitlePage','Title of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('SectionPage','Section of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('CategoryPage','Category of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('NamePage','Name of the Page','required|min_length[5]|callback_check_namepage[$str]|xss_clean|url_title');
$this->form_validation->set_rules('DescriptionPage','Description of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('BodyPage','Content of the Page','required|min_length[5]');
if($this->form_validation->run() == TRUE)
{
$page_inserted = $this->Create_Pages_Model->addPage();
redirect('dashboard', 'refresh');
}
else
{
$this->load->view('admin/user/add_new_page_view');
}
function check_namepage($str)
{
$PageName = $this->db->where('NamePage', $NamePage);
$query = $this->db->select('pages', array('NamePage' => $NamePage));
if($query == $PageName){
$this->form_validation->set_message('check_namepage', '%Should be Unique Name Page because we can\'t duplicate the URL of the page');
return FALSE;
}
elseif($NamePage != $query)
{
return TRUE;
}
}
}
else
{
$this->load->view('admin/user/add_new_page_view');
}
}
else
{
$this->load->view('view_error');
}
}
}
This is my model code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Create_Pages_Model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('view_error');
}
public function addPage(){
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['Username'] = $session_data['Username'];
$this->load->database();
$add_page = $this->input->post();
unset($add_page['insert']);
$this->db->insert('pages',$add_page);
return $this->db->insert_id();
}
else
{
$this->load->view('view_error');
}
}
}
And this this is my my view page,for insert the pages into the database:
<body>
<div id="main">
<div class="container">
<div class="page-header">
<h1>Create a New Page</h1>
</div>
<div class="row">
<div class="col-sm-12">
<p>Please enter your details below to form.</p>
<?php
$title_page = array(
'name' => 'TitlePage',
'id' => 'TitlePage',
'maxlength' => '490',
'size' => '90',
'type' => 'text',
'style' => 'position:relative;min-height:40px;width:100%;',
'value' => set_value('TitlePage'),
);
$section_page = array(
'name' => 'SectionPage',
'id' => 'SectionPage',
'maxlength' => '390',
'type' => 'text',
'size' => '90',
'style' => 'position:relative;min-height:40px;width:100%;',
'value' => set_value('SectionPage'),
);
$category_page = array(
'name' => 'CategoryPage',
'id' => 'CategoryPage',
'maxlength' => '290',
'type' => 'text',
'size' => '90',
'style' => 'position:relative;min-height:40px;width:100%;',
'value' => set_value('CategoryPage'),
);
$name_page = array(
'name' => 'NamePage',
'id' => 'NamePage',
'maxlength' => '290',
'type' => 'text',
'size' => '90',
'style' => 'position:relative;min-height:40px;width:100%;',
'value' => set_value('NamePage'),
);
$description_page = array(
'name' => 'DescriptionPage',
'id' => 'DescriptionPage',
'maxlength' => '290',
'type' => 'text',
'size' => '90',
'style' => 'position:relative;min-height:40px;width:100%;',
'value' => set_value('DescriptionPage'),
);
$body_page = array(
'name' => 'BodyPage',
'id' => 'BodyPage',
'maxlength' => '290',
'type' => 'text',
'size' => '90',
'style' => 'position:relative;min-height:320px;width:100%;',
'value' => set_value('BodyPage'),
'rows' => '15',
'cols' => '80',
);
?><?php echo form_open();?>
<?php echo form_label('Title of the Page:','lbl_titlepage');?><br/>
<?php echo form_input($title_page);?><?php echo form_error('TitlePage'); ?><br/>
<?php echo form_label('Section of the Page:','lbl_sectionpage');?><br/>
<?php echo form_input($section_page);?><?php echo form_error('SectionPage'); ?><br/>
<?php echo form_label('Category of the Page:','lbl_categorypage');?><br/>
<?php echo form_input($category_page);?><?php echo form_error('CategoryPage'); ?><br/>
<?php echo form_label('Name of the Page (URL):','lbl_namepage');?><br/>
<?php echo form_input($name_page);?><?php echo form_error('NamePage'); ?><br/>
<?php echo form_label('Description of the Page:','lbl_descriptionpage');?><br/>
<?php echo form_input($description_page);?><?php echo form_error('DescriptionPage'); ?><br/>
<?php echo form_label('Contentent of the Page:','lbl_BodyPage');?><br/>
<?php echo form_textarea($body_page);?><?php echo form_error('BodyPage'); ?><br/><br/>
<?php echo form_submit('insert','Create Page')?><br/>
<?php echo form_close();?>
</div>
</div>
</div>
</div>
</body>
</html>
And this is my database:
CREATE TABLE `pages` (
`ID_Page` int(11) NOT NULL,
`TitlePage` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`SectionPage` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`CategoryPage` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`NamePage` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`BodyPage` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`DescriptionPage` varchar(255) COLLATE utf8_spanish_ci NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
ALTER TABLE `pages`
ADD PRIMARY KEY (`ID_Page`);
ALTER TABLE `pages`
MODIFY `ID_Page` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10;
Move check_namepage() method outside of add_new_page() method.
and you do not need to pass $str in callback_check_namepage[$str]. It should be just callback_check_namepage because CI will automatically pass the user provided field data to the callback function. So, in the callback check_namepage($str), $str will be available automatically.
So, your Controller will be like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Create_Pages extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
/*$this->load->library('pagination');*/
$this->load->model('Create_Pages_Model');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['Username'] = $session_data['Username'];
}
else
{
$this->load->view('view_error');
}
}
public function add_new_page()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['Username'] = $session_data['Username'];
$this->load->view('view_admin_content_panel', $data);
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Create_Pages_Model');
$data_pages = array(
'TitlePage' => $this->input->post('TitlePage'),
'SectionPage' => $this->input->post('SectionPage'),
'CategoryPage' => $this->input->post('CategoryPage'),
'NamePage' => $this->input->post('NamePage'),
'DescriptionPage' => $this->input->post('DescriptionPage'),
'BodyPage' => $this->input->post('BodyPage')
);
if($this->input->post())
{
$this->form_validation->set_rules('TitlePage','Title of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('SectionPage','Section of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('CategoryPage','Category of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('NamePage','Name of the Page','required|min_length[5]|callback_check_namepage|xss_clean|url_title'); // [$str] is removed
$this->form_validation->set_rules('DescriptionPage','Description of the Page','required|min_length[5]|xss_clean');
$this->form_validation->set_rules('BodyPage','Content of the Page','required|min_length[5]');
if($this->form_validation->run() == TRUE)
{
// moved below
$page_inserted = $this->Create_Pages_Model->addPage();
redirect('dashboard', 'refresh');
}
else
{
$this->load->view('admin/user/add_new_page_view');
}
}
else
{
$this->load->view('admin/user/add_new_page_view');
}
}
else
{
$this->load->view('view_error');
}
}
private function check_namepage($str)
{
// you have error here, solve it
$PageName = $this->db->where('NamePage', $NamePage);
$query = $this->db->select('pages', array('NamePage' => $NamePage));
if($query == $PageName){
$this->form_validation->set_message('check_namepage', '%Should be Unique Name Page because we can\'t duplicate the URL of the page');
return FALSE;
}
elseif($NamePage != $query)
{
return TRUE;
}
}
}
I am new to CI.Can anyone help me giving tutorial for image uploading for CI 2.0.
I have make an folder Product_image in asset folder.My table name is tbl_product.my controller page is product and code is:
<?php
include_once('application/backend/controllers/dashboard.php');
class Product extends Dashboard {
function _construct(){
parent::_construct();
$this->load->model('product_model');
}
public function index() {
$this->islogin();
$data=$this->generateCommonItems();
$this->load->model('product_model');
$data['page_title']="List of Products";
$data['page_heading']="List of Products";
$data['listAllProduct']=$this->product_model->listAllProduct();
$this->load->view('products/listproduct',$data);
}
function addproduct() {
$this->data['title'] = 'Add Product';
//validate form input
$this->form_validation->set_rules('prod_name', 'Product name', 'required|xss_clean');
$this->form_validation->set_rules('prod_des', 'Description', 'required|xss_clean');
$this->form_validation->set_rules('price', 'Price', 'required|xss_clean');
$this->form_validation->set_rules('prod_image', 'Picture', 'required|xss_clean');
if ($this->form_validation->run() == true)
{
$data = array(
'prod_name' => $this->input->post('prod_name'),
'prod_des' => $this->input->post('prod_des'),
'price' => $this->input->post('price'),
'prod_image' => $this->input->post('prod_image')
);
$this->product_model->insert_product($data);
redirect('product/addproduct');
} else {
$data=$this->generateCommonItems();
//display the add product form
//set the flash data error message if there is one
$this->data['prod_name'] = array(
'name' => 'name',
'id' => 'name',
'type' => 'text',
'style' => 'width:300px;',
'value' => $this->form_validation->set_value('name'),
);
$this->data['prod_des'] = array(
'name' => 'description',
'id' => 'description',
'type' => 'text',
'cols' => 60,
'rows' => 5,
'value' => $this->form_validation->set_value('description'),
);
$this->data['price'] = array(
'name' => 'price',
'id' => 'price',
'type' => 'text',
'style' => 'width:40px;text-align: right',
'value' => $this->form_validation->set_value('price'),
);
$this->data['prod_image'] = array(
'value' => $this->form_validation->set_value('prod_image'),
);
$this->load->view('includes/header',$data);
$this->load->view('products/product_form', $this->data);
$this->load->view('includes/footer',$data);
}
}
public function delete($prod_id) {
$this->islogin();
$this->load->model('product_model');
if($this->product_model->deleteByid($prod_id))
redirect('product/index');
}
function edit_product($prod_id) {
$product = $this->product_model->get_product($prod_id);
$this->data['title'] = 'Edit Product';
//validate form input
$this->form_validation->set_rules('prod_name', 'Product name', 'required|xss_clean');$this->form_validation->set_rules('description', 'Description', 'required|xss_clean');
$this->form_validation->set_rules('price', 'Price', 'required|xss_clean');
$this->form_validation->set_rules('prod_image', 'Picture', 'required|xss_clean');
if (isset($_POST) && !empty($_POST))
{
$data = array(
'prod_name' => $this->input->post('prod_name'),
'prod_des' => $this->input->post('prod_des'),
'price' => $this->input->post('price'),
'prod_image' => $this->input->post('prod_image'),
);
if ($this->form_validation->run() === true)
{
$this->product_model->update_product($prod_id, $data);
redirect(base_url().'product/edit/'.$prod_id);
}
}
$this->data['tbl_product'] = $product;
//display the edit product form
$this->data['prod_name'] = array(
'name' => 'name',
'id' => 'name',
'type' => 'text',
'style' => 'width:300px;',
'value' => $this->form_validation->set_value('name', $product['name']),
);
$this->data['prod_des'] = array(
'name' => 'description',
'id' => 'description',
'type' => 'text',
'cols' => 60,
'rows' => 5,
'value' => $this->form_validation->set_value('description', $product['description']),
);
$this->data['price'] = array(
'name' => 'price',
'id' => 'price',
'type' => 'text',
'style' => 'width:40px;text-align: right',
'value' => $this->form_validation->set_value('price', $product['price']),
);
$this->data['prod_image'] = array(
'name' => 'picture',
'id' => 'picture',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('prod_image', $product['picture']),
);
$this->load->view('products/edit_product', $this->data);
}
}
my model page is product_model:
<?php class Product_model extends CI_Model {
function __construct() {
parent::__construct();
}
function listAllProduct() {
$query = $this->db->select('*')->from('tbl_product')->get();
//return $query = result();
//$query = $this->db->query("select * from tbl_product");
return $query->result();
}
function get_product($prod_id) {
$this->db->select('prod_id, prod_name, prod_des, price, prod_image');
$this->db->where('prod_id', $prod_id);
$query = $this->db->get('tbl_product');
return $query->row_array();
}
public function insert_product($data) {
if ($this->db->insert('tbl_product', $data))
return true;
else {
return false;
}
}
public function update_product($prod_id, $data) {
$this->db->where('prod_id', $prod_id);
$this->db->update('tbl_product', $data);
}
function deleteByid($prod_id) {
$this->db->where('prod_id', $prod_id);
if ($this->db->delete('tbl_product')) {
return true;
} else {
return false;
}
View:
<h2 align="center">Add Product</h2>
<?php echo form_open("product/addproduct");?>
<table width="700" border="1" cellpadding="0" cellspacing="2" align="center">
<tr>
<td width="130" align="right" bgcolor="#FFFFFF">Product Name: </td>
<td><?php echo form_input($prod_name);?></td>
</tr>
<tr>
<td width="130" align="right" bgcolor="#FFFFFF">Product Description: </td>
<td><?php echo form_textarea($prod_des); ?></td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFFF">Price:</td>
<td><?php echo form_input($price); ?></td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFFF">Picture:</td>
<td><?php echo form_input($prod_image); ?></td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFFF"> </td>
<td><?php echo form_submit('submit', 'Submit');?>
</tr>
</table>
<?php echo form_close(); ?>
Form page view:
<h2 align="center">Add Product</h2>
<?php echo form_open("product/addproduct");?>
<table width="700" border="1" cellpadding="0" cellspacing="2" align="center">
<tr>
<td width="130" align="right" bgcolor="#FFFFFF">Product Name: </td>
<td><?php echo form_input($prod_name);?></td>
</tr>
<tr>
<td width="130" align="right" bgcolor="#FFFFFF">Product Description: </td>
<td><?php echo form_textarea($prod_des); ?></td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFFF">Price:</td>
<td><?php echo form_input($price); ?></td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFFF">Picture:</td>
<td><?php echo form_input($prod_image); ?></td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFFF"> </td>
<td><?php echo form_submit('submit', 'Submit');?>
</tr>
</table>
<?php echo form_close(); ?>
I m thankful to him/her who give me solution for this error code by checking mistake n error?
1: You have to use the attribute open_multipart when uploading files in forms:
<?php echo form_open_multipart('product/addproduct');?>
2: Take off the file form attrribute from the form validation: Delete this:
$this->form_validation->set_rules('prod_image', 'Picture', 'required|xss_clean');
3: Use this to save the file in folder:
$config['upload_path'] = './asset/Product_image/'; //The path where the image will be save
$config['allowed_types'] = 'gif|jpg|png'; //Images extensions accepted
$config['max_size'] = '2048'; //The max size of the image in kb's
$config['max_width'] = '1024'; //The max of the images width in px
$config['max_height'] = '768'; //The max of the images height in px
$config['overwrite'] = TRUE; //If exists an image with the same name it will overwrite. Set to false if don't want to overwrite
$this->load->library('upload', $config); //Load the upload CI library
if (!$this->upload->do_upload('userfile')){
$uploadError = array('upload_error' => $this->upload->display_errors());
$this->set_flashdata('uploadError', $uploadError, $urlYouWantToReturn); //If for some reason the upload could not be done, returns the error in a flashdata and redirect to the page you specify in $urlYouWantToReturn
exit;
}
4: After that, you gonna grab the file name to save the file reference in Database. Put right below:
$file_info = $this->upload->data('userfile');
$file_name = $file_info['file_name']; //Now you got the file name in the $file_name var. Use it to record in db.
//You can assign it to your data array to pass to your update_product function.
5: Now, the whole code merged:
function addproduct() {
$this->data['title'] = 'Add Product';
//validate form input
$this->form_validation->set_rules('prod_name', 'Product name', 'required|xss_clean');
$this->form_validation->set_rules('prod_des', 'Description', 'required|xss_clean');
$this->form_validation->set_rules('price', 'Price', 'required|xss_clean');
if ($this->form_validation->run() == true)
{
$config['upload_path'] = './asset/Product_image/'; //The path where the image will be save
$config['allowed_types'] = 'gif|jpg|png'; //Images extensions accepted
$config['max_size'] = '2048'; //The max size of the image in kb's
$config['max_width'] = '1024'; //The max of the images width in px
$config['max_height'] = '768'; //The max of the images height in px
$config['overwrite'] = TRUE; //If exists an image with the same name it will overwrite. Set to false if don't want to overwrite
$this->load->library('upload', $config); //Load the upload CI library
if (!$this->upload->do_upload('userfile')){
$uploadError = array('upload_error' => $this->upload->display_errors());
$this->set_flashdata('uploadError', $uploadError, $urlYouWantToReturn); //If for some reason the upload could not be done, returns the error in a flashdata and redirect to the page you specify in $urlYouWantToReturn
exit;
}
$file_info = $this->upload->data('userfile');
$file_name = $file_info['file_name']; //Now you got the file name in the $file_name var. Use it to record in db.
$data = array(
'prod_name' => $this->input->post('prod_name'),
'prod_des' => $this->input->post('prod_des'),
'price' => $this->input->post('price'),
'prod_image'=> $file_name,
);
$this->product_model->insert_product($data);
redirect('product/addproduct');
} else {
$data=$this->generateCommonItems();
//display the add product form
//set the flash data error message if there is one
$this->data['prod_name'] = array(
'name' => 'name',
'id' => 'name',
'type' => 'text',
'style' => 'width:300px;',
'value' => $this->form_validation->set_value('name'),
);
$this->data['prod_des'] = array(
'name' => 'description',
'id' => 'description',
'type' => 'text',
'cols' => 60,
'rows' => 5,
'value' => $this->form_validation->set_value('description'),
);
$this->data['price'] = array(
'name' => 'price',
'id' => 'price',
'type' => 'text',
'style' => 'width:40px;text-align: right',
'value' => $this->form_validation->set_value('price'),
);
$this->data['prod_image'] = array(
'value' => $this->form_validation->set_value('prod_image'),
);
$this->load->view('includes/header',$data);
$this->load->view('products/product_form', $this->data);
$this->load->view('includes/footer',$data);
}
}
This is what i use in my CI projects, hope it helps!
You can upload images with form by giving it an attribute of enctype.
<?php echo form_open_multipart('product/addproduct');?>
<input type="file" name="userfile" size="20" />
<input type="submit" value="Submit">
<?php echo form_close();?>
CodeIgniter also have some helper classes that can be found in the documentation. Here's one:
http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html