Here is my issue:
I'm trying to creta a pagination for my blog page, but for some reason I try to put the number of entries that I want displayed, and it do not work. I do not know why?; any help will be helpful, thanks.
Here is my controller:
public function blog()
{
// Pagination for Blog //
$data['blog'] = $this->blog_model->get_blog();
$data['categorias'] = $this->categorias_model->get_categorias();
$data['title'] = 'Blog';
$this->load->library('pagination');
$config['base_url'] = site_url('/blog/');
$config['total_rows'] = 200;
$config['per_page'] = 1;
$config['uri_segment'] = 3;
$config['num_links'] = 2;
$config['use_page_numbers'] = TRUE;
$config['page_query_string'] = TRUE;
$this->pagination->initialize($config);
$this->data['pagination'] = $this->pagination->create_links();
$this->load->view('templates/head',$data);
$this->load->view('templates/navbar',$data);
$this->load->view('news\blog\index.php',$this->data);
$this->load->view('templates/footer',$data);
}
My model:
<?php
class Blog_model extends CI_Model{
// Connect to database //
public function __construct(){
$this->load->database();
}
// Get Posts from database //
public function get_blog($slug=FALSE){
if($slug===FALSE){
// Post order, ASC-DESC Categorias/Tags tabels //
$this->db->order_by('blog.id', 'DESC');
$query=$this->db->get('blog');
return $query->result_array();
}
$query=$this->db->get_where('blog', array('slug'=>$slug));
return $query->row_array();
}
public function crear_post(){
$slug=url_title($this->input->post('titulo'));
$data = array(
'titulo' => $this->input->post('titulo'),
'slug' => $slug,
'imagen' => $this->input->post('imagen'),
'fecha' => $this->input->post('fecha'),
'contenido' => $this->input->post('contenido'),
'categoria_id' => $this->input->post('categoria_id'),
);
return $this->db->insert('blog',$data);
}
public function delete_post($id){
$this->db->where('id', $id);
$this->db->delete('blog');
return true;
}
public function update_post(){
$slug = url_title($this->input->post('titulo'));
$data = array(
'titulo' => $this->input->post('titulo'),
'slug' => $slug,
'imagen' => $this->input->post('imagen'),
'fecha' => $this->input->post('fecha'),
'contenido' => $this->input->post('contenido'),
'categoria_id' => $this->input->post('categoria_id'),
);
$this->db->where('id', $this->input->post('id'));
return $this->db->update('blog', $data);
}
}
And here is my view:
<div class="col-md-8 animated fadeIn">
<?php foreach($blog as $blog) : ?>
<div class="card text-xs-left"><!-- FIRST ARTICLE DEMO -->
<div class="card-header" id="article-header">
<h4><?php echo ucfirst($blog['titulo']); ?></h4>
</div>
<img src="<?php echo $blog['imagen']; ?>" width="750" heihgt="350" class="img-fluid">
<!--<div class="card-body">
<p> <?php echo word_limiter($blog['contenido'],5); ?></p>
</div>-->
<div class="card-footer" id="article-footer">
<div class="row">
<div class="col-lg-12 col-md-9 col-sm-8">
<i class="fa fa-calendar" aria-hidden="true"></i> <?php echo ucfirst($blog['fecha']); ?>
<i class="fa fa-folder" aria-hidden="true"></i> <?php echo $blog['categoria_id']; ?>
Read more ยป
</div>
</div>
</div>
</div>
<?php endforeach ?>
<!-- /Article -->
<?php echo $pagination ?>
</div>
here is again:
my controller:
public function blog() {
$data['blog'] = $this->blog_model->get_blog();
$data['categorias'] = $this->categorias_model->get_categorias();
$data['title'] = 'Blog';
$config = array();
$config["base_url"] = base_url() . "blog";
$config["total_rows"] = $this->blog_model->record_count();
$config["per_page"] = 1;
$config["uri_segment"] = 3;
$config['num_links'] = 1;
$config['query_string_segment'] = 'paginas';
$config['page_query_string'] = TRUE;
$config['display_pages'] = FALSE;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["pagination"] = $this->pagination->create_links();
$data["results"] = $this->blog_model->get_paginas($config["per_page"], $page);
$this->load->view('templates/head',$data);
$this->load->view('templates/navbar',$data);
$this->load->view("news/blog/index", $data);
$this->load->view('templates/footer',$data);
}
and then again, my model:
class Blog_model extends CI_Model{
// Connect to database //
public function __construct(){
$this->load->database();
}
// Get Posts from database //
public function get_blog($slug=FALSE){
if($slug===FALSE){
// Post order, ASC-DESC Categorias/Tags tabels //
$this->db->order_by('blog.id', 'DESC');
// $this->db->join('categorias','categorias.id = blog.categoria_id');
// /Post order, ASC-DESC //
$query=$this->db->get('blog');
return $query->result_array();
}
$query=$this->db->get_where('blog', array('slug'=>$slug));
return $query->row_array();
}
///Pagination
public function record_count() {
return $this->db->count_all("blog");
}
public function get_paginas($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("blog");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
// Crear post //
public function crear_post(){
$slug=url_title($this->input->post('titulo'));
$data = array(
'titulo' => $this->input->post('titulo'),
'slug' => $slug,
'imagen' => $this->input->post('imagen'),
// 'autor' => $this->input->post('autor'),
'fecha' => $this->input->post('fecha'),
'contenido' => $this->input->post('contenido'),
'categoria_id' => $this->input->post('categoria_id'),
);
return $this->db->insert('blog',$data);
}
// Borrar post //
public function delete_post($id){
$this->db->where('id', $id);
$this->db->delete('blog');
return true;
}
// Actualizar Post //
public function update_post(){
$slug = url_title($this->input->post('titulo'));
$data = array(
'titulo' => $this->input->post('titulo'),
'slug' => $slug,
'imagen' => $this->input->post('imagen'),
// 'autor' => $this->input->post('autor'),
'fecha' => $this->input->post('fecha'),
'contenido' => $this->input->post('contenido'),
'categoria_id' => $this->input->post('categoria_id'),
);
$this->db->where('id', $this->input->post('id'));
return $this->db->update('blog', $data);
}
// Categorias //
// public function get_categorias(){
// $this->db->order_by('nombre');
// $query = $this->db->get('categorias');
// return $query->result_array();
// }
}
Related
I have the following select box which lists the all users. I need list users only which groupID is==3 How can I do that ?
Thanks in advance
<div class="form-group " >
<label for="Staff" class=" control-label col-md-4 text-left"> Staff </label>
<div class="col-md-7">
<select name='Staff' rows='5' id='Staff' class='select2 ' ></select>
</div>
<div class="col-md-1">
</div>
</div>
Controller
use App\Http\Controllers\controller; use App\Models\Adminorders; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator as Paginator; use Validator, Input, Redirect ;
class AdminordersController extends Controller {
protected $layout = "layouts.main";
protected $data = array();
public $module = 'adminorders';
static $per_page = '10';
public function __construct()
{
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->model = new Adminorders();
$this->modelview = new \App\Models\Orderdetail();
$this->info = $this->model->makeInfo( $this->module);
$this->access = $this->model->validAccess($this->info['id']);
$this->data = array(
'pageTitle' => $this->info['title'],
'pageNote' => $this->info['note'],
'pageModule'=> 'adminorders',
'return' => self::returnUrl()
);
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array());
}
public function getIndex( Request $request )
{
if($this->access['is_view'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$sort = (!is_null($request->input('sort')) ? $request->input('sort') : 'SiparisID');
$order = (!is_null($request->input('order')) ? $request->input('order') : 'asc');
// End Filter sort and order for query
// Filter Search for query
$filter = '';
if(!is_null($request->input('search')))
{
$search = $this->buildSearch('maps');
$filter = $search['param'];
$this->data['search_map'] = $search['maps'];
}
$page = $request->input('page', 1);
$params = array(
'page' => $page ,
'limit' => (!is_null($request->input('rows')) ? filter_var($request->input('rows'),FILTER_VALIDATE_INT) : static::$per_page ) ,
'sort' => $sort ,
'order' => $order,
'params' => $filter,
'global' => (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
);
// Get Query
$results = $this->model->getRows( $params );
// Build pagination setting
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($results['rows'], $results['total'], $params['limit']);
$pagination->setPath('adminorders');
$this->data['rowData'] = $results['rows'];
// Build Pagination
$this->data['pagination'] = $pagination;
// Build pager number and append current param GET
$this->data['pager'] = $this->injectPaginate();
// Row grid Number
$this->data['i'] = ($page * $params['limit'])- $params['limit'];
// Grid Configuration
$this->data['tableGrid'] = $this->info['config']['grid'];
$this->data['tableForm'] = $this->info['config']['forms'];
// Group users permission
$this->data['access'] = $this->access;
// Detail from master if any
// Master detail link if any
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
// Render into template
return view('adminorders.index',$this->data);
}
function getUpdate(Request $request, $id = null)
{
if($id =='')
{
if($this->access['is_add'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
if($id !='')
{
if($this->access['is_edit'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
$row = $this->model->find($id);
if($row)
{
$this->data['row'] = $row;
} else {
$this->data['row'] = $this->model->getColumnTable('tb_orders');
}
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['forms']);
$relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);
$this->data['accesschild'] = $this->modelview->validAccess($relation_key['id']);
$this->data['relation_key'] = $relation_key['key'];
$this->data['subform'] = $this->detailview($this->modelview , $this->info['config']['subform'] ,$id );
$this->data['id'] = $id;
return view('adminorders.form',$this->data);
}
public function getShow( Request $request, $id = null)
{
if($this->access['is_detail'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$row = $this->model->getRow($id);
if($row)
{
$this->data['row'] = $row;
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['grid']);
$this->data['id'] = $id;
$this->data['access'] = $this->access;
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
$this->data['prevnext'] = $this->model->prevNext($id);
return view('adminorders.view',$this->data);
} else {
return Redirect::to('adminorders')->with('messagetext','Record Not Found !')->with('msgstatus','error');
}
}
function postSave( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_adminorders');
$id = $this->model->insertRow($data , $request->input('SiparisID'));
$this->detailviewsave( $this->modelview , $request->all() ,$this->info['config']['subform'] , $id) ;
if(!is_null($request->input('apply')))
{
$return = 'adminorders/update/'.$id.'?return='.self::returnUrl();
} else {
$return = 'adminorders?return='.self::returnUrl();
}
// Insert logs into database
if($request->input('SiparisID') =='')
{
\SiteHelpers::auditTrail( $request , 'New Data with ID '.$id.' Has been Inserted !');
} else {
\SiteHelpers::auditTrail($request ,'Data with ID '.$id.' Has been Updated !');
}
return Redirect::to($return)->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders/update/'.$request->input('SiparisID'))->with('messagetext',\Lang::get('core.note_error'))->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
public function postDelete( Request $request)
{
if($this->access['is_remove'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
// delete multipe rows
if(count($request->input('ids')) >=1)
{
$this->model->destroy($request->input('ids'));
\DB::table('tb_orderdetail')->whereIn('SiparisID',$request->input('ids'))->delete();
\SiteHelpers::auditTrail( $request , "ID : ".implode(",",$request->input('ids'))." , Has Been Removed Successfull");
// redirect
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext', \Lang::get('core.note_success_delete'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext','No Item Deleted')->with('msgstatus','error');
}
}
public static function display( )
{
$mode = isset($_GET['view']) ? 'view' : 'default' ;
$model = new Adminorders();
$info = $model::makeInfo('adminorders');
$data = array(
'pageTitle' => $info['title'],
'pageNote' => $info['note']
);
if($mode == 'view')
{
$id = $_GET['view'];
$row = $model::getRow($id);
if($row)
{
$data['row'] = $row;
$data['fields'] = \SiteHelpers::fieldLang($info['config']['grid']);
$data['id'] = $id;
return view('adminorders.public.view',$data);
}
} else {
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$params = array(
'page' => $page ,
'limit' => (isset($_GET['rows']) ? filter_var($_GET['rows'],FILTER_VALIDATE_INT) : 10 ) ,
'sort' => 'SiparisID' ,
'order' => 'asc',
'params' => '',
'global' => 1
);
$result = $model::getRows( $params );
$data['tableGrid'] = $info['config']['grid'];
$data['rowData'] = $result['rows'];
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($result['rows'], $result['total'], $params['limit']);
$pagination->setPath('');
$data['i'] = ($page * $params['limit'])- $params['limit'];
$data['pagination'] = $pagination;
return view('adminorders.public.index',$data);
}
}
function postSavepublic( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_orders');
$this->model->insertRow($data , $request->input('SiparisID'));
return Redirect::back()->with('messagetext','<p class="alert alert-success">'.\Lang::get('core.note_success').'</p>')->with('msgstatus','success');
} else {
return Redirect::back()->with('messagetext','<p class="alert alert-danger">'.\Lang::get('core.note_error').'</p>')->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
}
I am having a syntax issue in the controller in the function index where the view is being loaded. it is saying that I have Severity: Parsing Error
Message: syntax error, unexpected ';' I cannot figure out what the issue is I am trying to get the count of all my records in the database. Any help would be appreciated.
controllers/test.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('test_model','test_table');
}
public function index()
{
$this->load->view('includes/header');
$this->load->view('includes/table_main');
$this->load->view('includes/ajax_functions');
$this->load->view('includes/add_employee_form');
$total_records = $this->test_model->count_all_records();
//$this->load->view('test_view');
$this->load->view('test_view', array('total_records' => $total_records);
}
public function ajax_list()
{
$list = $this->test_table->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $test_table) {
$no++;
$row = array();
$row[] = $test_table->Name;
$row[] = $test_table->Department;
$row[] = $test_table->Manager;
//add html for action
$row[] = '<a class="btn btn-sm btn-link " href="javascript:void()" title="Edit" onclick="edit_test('."'".$test_table->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm text-warning" href="javascript:void()" title="Hapus" onclick="delete_test('."'".$test_table->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->test_table->count_all(),
"recordsFiltered" => $this->test_table->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->test_table->get_by_id($id);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'Name' => $this->input->post('Name'),
'Department' => $this->input->post('Department'),
'Manager' => $this->input->post('Manager'),
);
$insert = $this->test_table->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'Name' => $this->input->post('Name'),
'Department' => $this->input->post('Department'),
'Manager' => $this->input->post('Manager'),
);
$this->test_table->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->test_table->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
//validation section were user must enter data in all fields
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('Name') == '')
{
$data['inputerror'][] = 'Name';
$data['error_string'][] = 'Name is required';
$data['status'] = FALSE;
}
if($this->input->post('Department') == '')
{
$data['inputerror'][] = 'Department';
$data['error_string'][] = 'Department is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class test_model extends CI_Model {
var $table = 'test_table';
var $column = array('Name','Department','Manager'); //set column field database for order and search
var $order = array('id' => 'desc'); // default order
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$column[$i] = $item; // set column array variable to order processing
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function count_all_records(){
$this->db->select('id');
$this->db->distinct();
$this->db->from('test_table');
$query = $this->db->get();
return $query->num_rows();
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
view
Total Records: <?php echo $total_records ?>
In the class Test index function last statement ) is missing. Here is the correct one
$this->load->view('test_view', array('total_records' => $total_records));
It might cause due to script contain in view ,set short_open_tag 0 in your htaccess file and check if solves
<IfModule mod_php5.c >
php_value short_open_tag 0
</IfModule >
Could someone please enlighten me as to what I'm doing incorrectly - I'm currently following a net tuts+ video, which goes through the process of listing an array of posts, and then having the ability to click on one post, to be shown the detail.
I'm adapting the above method for my own solution/web application, but I'm at a loss as to why my array is blank.
I'm using this line to create link/anchor to the next controller
<a href="<?php echo base_url(); ?>Search/site/<?php echo $site->siteID; ?>"><?php echo $site->site_title; ?>
I've highlighted the code where I believe I'm going a miss,
Thanks
Controller
class Search extends CI_Controller {
public function display($sort_by = 'site_title', $sort_order = 'asc', $offset = 0)
{
$limit = 20;
$data['columns'] = array(
'site_title' => 'Site Name',
'site_uprn' => 'Unique Property Reference'
);
$this->load->model('search_model');
$results = $this->search_model->search_sites($limit, $offset, $sort_by, $sort_order);
$data['sites'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
//pagination
$this->load->library('pagination');
$config = array ();
$config['base_url'] = site_url("Search/display/$sort_by/$sort_order");
$config['total_rows'] = $data['num_results'];
$config['per_page'] = $limit;
$config['uri_segment'] = 5;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$data['sort_by'] = $sort_by;
$data['sort_order'] = $sort_order;
$this->load->view('search', $data);
}
**function site($siteID){
$this->load->model('search_model');
$data['site_detail']=$this->search_model->site_detail($siteID);
//$this->load->view('site', $data);
}
}**
Model
<?php
class Search_model extends CI_Model {
function search_sites($limit, $offset, $sort_by, $sort_order){
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('site_title', 'site_uprn');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'site_title';
//site table
$q = $this->db->select('siteID, site_title, site_uprn')
->from('sites')
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
$ret['rows'] = $q->get()->result();
//count query
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('sites');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
**//sites details
function site_detail($siteID){
$this->db->select()->from('sites')->where('siteID', $siteID);
$query = $this->db->get();
return $query->first_row('array');
}
}**
View
<div id="right">
<h5>Site Details</h5>
<ul>
<li><?php $site_detail['siteID']?></li>
<li><?php $site_detail['site_title']?></li>
</div>
Hi everyone I am new to CodeIgniter and PHP.
I'm trying to create pagination on one of my pages, but my code doesn't display the pagination on the page for some reason.
view.php
</head>
<body>
<h1>Answer</h1>
<?php if (isset($records)) : foreach($records as $row) : ?>
<div = 'container'>
<?php
if (isset($pagination))
{
echo $pagination;
}
?>
<ul>
<h1><?php echo $row->question; ?></h1>
<li><?php echo $row->answer1; ?></li>
<li><?php echo $row->answer2; ?></li>
<li><?php echo $row->answer3; ?></li>
<li><?php echo $row->answer4; ?></li>
<li><?php echo $row->answer5; ?></li>
<li><?php echo $row->answer6; ?></li>
<ul>
</div>
<?php endforeach; ?>
<?php else : ?>
<h2>no records were returned</h2>
<?php endif; ?>
</body>
</html>
control.php
<?php
class Survey extends CI_Controller{
function index()
{
$data = array(
'question' => $this->input->post('question'),
'answer1' => $this->input->post('answer1'),
'answer2' => $this->input->post('answer2'),
'answer3' => $this->input->post('answer3'),
'answer4' => $this->input->post('answer4'),
'answer5' => $this->input->post('answer5'),
'answer6' => $this->input->post('answer6'),
);
if($query = $this->membership_model->get_records())
{
$data['records'] = $query;
}
$this->load->view('survey_view', $data);
}
//pagination
function page()
{
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/admin/index.php/survey/index';
$config['total_rows'] = $this->db->get('save_survey')->num_rows();
$config['per_page'] = 1;
$config['num_links'] =10;
$this->pagination->initialize($config);
$data['records'] = $this->db-get('save_survey', $config['per_page'], $this->uri->segment(3));
$data['pagination'] = $this->pagination->create_links();
$this->load->view('survey_view', $data);
}
}
?>
The function page() is never called.
When you navigate to the controller then the default index() function will be triggered. And in that function there is no call to page(); method.
I never used the pagination stuff of CI before, but to include your pagination code (page()) in the index() method, you can do it like this (I removed the view from the page method):
class Survay extends CI_Controller{
function index() {
$data = array(
'question' => $this->input->post('question'),
'answer1' => $this->input->post('answer1'),
'answer2' => $this->input->post('answer2'),
'answer3' => $this->input->post('answer3'),
'answer4' => $this->input->post('answer4'),
'answer5' => $this->input->post('answer5'),
'answer6' => $this->input->post('answer6'),
);
if($query = $this->membership_model->get_records()) {
$data['records'] = $query;
}
//call your page method and set the pagination variables to this object
$this->page();
//show the view
$this->load->view('survay_view', $data);
}
//pagination ONLY sets the pagination variables
function page() {
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/admin/index.php/survay/index';
$config['total_rows'] = $this->db->get('save_survay')->num_rows();
$config['per_page'] = 1;
$config['num_links'] = 10;
$this->pagination->initialize($config);
$data['records'] = $this->db-get('save_survay', $config['per_page'], $this->uri->segment(3));
$data['pagination'] = $this->pagination->create_links();
}
}
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.