Variable from view to model. MVC - php

I am a beginner and wrote a web page based on the tutorial JREAM (MVC).
I've encountered a problem in displaying articles.
How can I send a variable $from (index.php) from the controller to the model?
Of course, I can connect to the database in the index.php but whether that is good?
index.php
$limit = LIMIT; // article per page
$article = $this->Ile[0]['num']; // number of articles
if (isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$allpage = round($article/$limit);
$from = $limit * ($page - 1);
// $from send value to model and model return array with article
foreach($this->Article as $key => $value)
{
echo '<div style="float:left;width:660px;"><hr/><br/><p><span class="strong" style="color:#CC0000;">';
echo $value['title'];
echo '</span></p><br/><p>';
echo $value['content'];
echo '</p><div style="height:130px;">';
echo $value['photo'];
echo '</div></div>';
}
echo '<hr/>';
echo '<div style="width: 660px; position: relative; pointer-events: none; text-align: center; top: 14px;">'.$page.' z '.$allpage.'</div>';
if ($page == 1 && $page < $allpage)
{
echo 'STARSZE >>';
}
elseif ($page >= $allpage)
{
echo '<< NOWSZE';
} else {
echo '<< NOWSZE';
echo 'STARSZE >>';
}
?>
news.php
class News extends Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->view->title = 'News';
$this->view->Ile = $this->model->Ile();
$this->view->Article = $this->model->Article();
// I can put some value in ...->Article(0); and it works, but how connect in index.php
$this->view->render('header');
$this->view->render('news/index');
$this->view->render('footer');
}
}
news_model.php
<?php
class News_Model extends Model
{
public function __construct()
{
parent::__construct();
}
public function Ile()
{
return $this->db->select('SELECT COUNT(*) as num FROM `articles`');
}
public function Article($from)
{
return $this->db->select('SELECT * FROM `articles` ORDER BY `newsid` DESC LIMIT '.$from.', '.LIMIT.'');
}
}
Regards,
Thomas

You should do this in your controller not in view :
Controller :
$limit = LIMIT; // article per page
$article = $this->view->Ile[0]['num']; // number of articles
if (isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$allpage = round($article/$limit);
$from = $limit * ($page - 1);
$this->view->Article = $this->model->Article($form); // This is how you can pass $form to model
And then you can assign This variable to your view like :
$this->view->page = $page
$this->view->allpage = $allpage
Now in view you can use $this->page instead of $page, same for $allpage
Hope it helps

Related

Codeigniter- Pagination-showing empty data after delete/edit

I am listing the registered employee from the db and showing 10 employee per page. I'm using codeigniter pagination for the purpose.
If I deleted an employee in page 2, after deleting I need to go to page 2 showing rest of the employees in page 2.
View:
<a href="<?php echo $path;?>welcome/delete_employee/employeeid/<?php echo $row->empID;?>/pageNum/<?php echo $currentPage; ?>" onClick="return delAlert()";><img src="<?php echo $path;?>/img/delete.png" height="30px" width="30px" /></a>
Controller:
public function delete_employee()
{
$session_id = $this->session->userdata('logged_in');
if($session_id) {
$array = $this->uri->uri_to_assoc(3);
$count=$array['pageNum']-1;
$i=$count*10;
$this->load->model('welcomemodel','m',true);
$this->m->deleteemployee($array['employeeid']);
$config = array();
$config["base_url"] = base_url() . "welcome/employee";
$config["total_rows"] =$this->m->employee_count();
$config["per_page"] = 10;
$config["uri_segment"] = $array['pageNum'];
$data['showData'] = $this->m->getEmployee($config["per_page"], $i);
$this->pagination->initialize($config);
$data["links"] = $this->pagination->create_links();
$data["currentPage"] =$array['pageNum'];
$this->load->view('header');
$this->load->view('employee',$data);
} else {
$this->load->view('session_expired');
}
}
Model:
public function deleteemployee($employeeid)
{
$this->db->where('empID',$employeeid);
$this->db->delete('employee');
return $this->db->affected_rows();
}
public function getEmployee($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->select()
->from('employee')
->order_by('emp_fname');
$this->db->join('service', 'employee.serviceID = service.serviceID','left');
$query=$this->db->get();
return $query;
}
public function employee_count()
{
return $this->db->count_all("employee");
}
But now the pagination link shows first page's link,even though contents of second page is displayed....
model method
public function employee_count()
{
$result = $this->db->get('employee');
if ($result->num_rows() > 0) {
//employee record available
return true;
}
else
{
// employee record not available
return false;
}
}
View
<?php
$getData = $this->[your model name]->getEmployee($limit, $start);
?>
<?php if ($getData): ?>
//Your Pagination Part Here.....
<?php else: ?>
// else Nothing
<?php endif ?>

Change title on page

I have the following code that change Title on the page:
class.php
<?php
class Title_And_Page
{
public $pagekey;
public $title;
public $page;
private $pages = array(
'start_page' => array("Startsida", "start_page.php"),
'products' => array("Produkter", "products.php"),
'max_ot' => array("Max-OT", "max_ot.php"),
'blog' => array("Blogg", "blog.php"),
'tools' => array("Verktyg", "tools.php"),
'about_us' => array("Om oss", "about_us.php"));
public function __construct($pagekey)
{
$this->pagekey = $pagekey;
}
public function setTitle()
{
if(array_key_exists($this->pagekey, $this->pages))
{
$this->title = $this->pages[$this->pagekey][0]; //Returns the value in title, that it gets when the constructs is run
return $this->title;
}
}
public function includePage()
{
if(array_key_exists($this->pagekey, $this->pages))
{
$this->page = $this->pages[$this->pagekey][1]; //Returns the value in page, that will be included
return $this->page;
}
}
}
?>
Here is my some code from my index.php
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
$page_title = new Title_And_Page($page);
<title><?= $page_title->setTitle(); ?></title>
<li id="info"><a href="?page=products" class='clickme'>Produkter</a></li>
<li id="info">MAX-OT</li>
<li id="info">Blogg</li>
<li id="info">Verktyg</li>
<li id="info">Om oss</li>
This works. However, I have articles in the blog page that contains "Read more"-links. When I click on a "Read more"-link, the URL changes to this: index.php?page=blog&readmore_from_firstpage=1&article_header=Vilken kolhydrat är bäst att äta efter träningen?
How can I change the title of the page, to the value in $_GET['article_header'] as you can see above?
Just extend your GET checks:
if(isset($_GET['article_header']))
{
$page = $_GET['article_header'];
}
elseif(isset($_GET['page']))
{
$page = $_GET['page'];
}
But since you're checking in your class whether that page is whitelisted, you'd need to either add another variable to force avoiding such check or simply just to print out the title if article_header is present.
Here's an example of the latter:
$avoidClass = false;
if(isset($_GET['article_header']))
{
$page = $_GET['article_header'];
$avoidClass = true;
}
elseif(isset($_GET['page']))
{
$page = $_GET['page'];
}
Then in HTML:
<title><?= $avoidClass ? $page : $page_title->setTitle(); ?></title>
Or, probably the simplest way:
if(isset($_GET['article_header']))
{
$page_title = $_GET['article_header'];
}
elseif(isset($_GET['page']))
{
$page_title = new Title_And_Page($_GET['page'])->setTitle();
}
else
{
$page_title = 'Default title here';
}
HTML
<title><?= $page_title ?></title>

CodeIgniter Search Results Pagination

Well I've searched and searched all around but I still can't find a solution to my problem. I'm still new to php and codeigniter so maybe I missed the answer already but anyways, here's what I'm trying to do.
This is my Controller (c_index.php) - calls a search function and performs pagination on the resulting array.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_index extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('m_search');
$this->load->library("pagination");
$this->load->library("table");
}
/** Index Page for this controller */
public function index()
{
if($this->session->userdata('logged_in')){
$this->load->view('v_user');
}
else{
$this->load->view('index');
}
}
public function search()
{
// start of search
$search_term = $this->input->post('word');
$books = $this->m_search->search_books($search_term);
// start of pagination
$config['base_url'] = "http://localhost/test/index.php/c_index/search";
$config['per_page'] = 5;
$config['num_links'] = 7;
$config['total_rows'] = count($books);
echo $config['total_rows'];
$this->pagination->initialize($config);
$data['query'] = array_slice($books,$this->uri->segment(3),$config['per_page']);
$this->load->view("index",$data);
}
}
Here's my view (index.php) - basically just displays the pagination result
<h3> Search Results </h3>
<!-- table -->
<table class="table table-condensed table-hover table-striped" id="result_table">
<tbody>
<?php
if(isset ($query)){
if(count($query)!=0){
foreach($query as $item){
echo "<tr><td>". $item['title'] ." by " .$item['author'] ."<br/></td></tr>";
}
echo $this->pagination->create_links();
}
else
{
echo "No results found for keyword ' ". $this->input->post('word')." ' .";
}
}
else
{
echo "Start a search by typing on the Search Bar";
}
?>
</tbody>
</table>
My model (m_search.php) - basically searches the database and returns an array of results.
<?php
class M_search extends CI_Model{
function search_books($search_term='default')
{
$filter = $this->input->post('filter');
//echo $filter;
if($filter == 'title')
{
//echo 'title';
$this->db->select('*');
$this->db->from('book');
$this->db->like('title',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else if($filter == 'author')
{
//echo 'author';
$this->db->select('*');
$this->db->from('book');
$this->db->like('author',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else if($filter == 'type')
{
//echo 'type';
$this->db->select('*');
$this->db->from('book');
$this->db->like('book_type',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else if($filter == 'status')
{
//echo 'status';
$this->db->select('*');
$this->db->from('book');
$this->db->like('book_status',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else
{
//echo 'all';
$this->db->select('*');
$this->db->from('book');
$this->db->like('book_status',$search_term);
$this->db->or_like('book_type',$search_term);
$this->db->or_like('author',$search_term);
$this->db->or_like('title',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}
}
}
Now my problem is keeping the results for the pagination.
The first page is fine but whenever I click on a page link, the results on the table show the whole database and is not limited to my search results.
I've read somewhere that I need to use sessions to keep my search_term so that it works when I switch pages but I don't know where to put it.
Any advice or suggestions would be greatly appreciated. Thanks.
There are several of different ways to handle search and pagination depending on your needs. Based on your existing code, this is what I would do.
Change
$search_term = $this->input->post('word');
to
$search_term = ''; // default when no term in session or POST
if ($this->input->post('word'))
{
// use the term from POST and set it to session
$search_term = $this->input->post('word');
$this->session->set_userdata('search_term', $search_term);
}
elseif ($this->session->userdata('search_term'))
{
// if term is not in POST use existing term from session
$search_term = $this->session->userdata('search_term');
}
function search_books($search_term='default')
{
$filter = $this->input->post('filter');
//echo $filter;
if($filter == 'title')
{
$this->db->like('title',$search_term);
}
else if($filter == 'author')
{
$this->db->like('author',$search_term);
}
else if($filter == 'type')
{
$this->db->like('book_type',$search_term);
}
else if($filter == 'status')
{
$this->db->like('book_status',$search_term);
}
else
{
$this->db->like('book_status',$search_term);
$this->db->or_like('book_type',$search_term);
$this->db->or_like('author',$search_term);
$this->db->or_like('title',$search_term);
// Execute the query.
}
$query = $this->db->get('book');
return $query->result_array();
}
}
Just trying to lessen your Model code, if you don't want to use "session" and want to copy, paste link/url and get same result in your search then you should use uri class in your controller.
you can use following code in your controller all query string will show in pagination links.
$config['reuse_query_string']=TRUE;
for additional parameters in paging link you can un comment following 2 lines.
//$getData = array('s'=>$search);
//$config['suffix'] = '?'.http_build_query($getData,'',"&");
$this->pagination->initialize($config);
Try in this way in your Controller,
public function search()
{
$result=array();
if($this->session->userdata('login_id')!='')
{
$q = trim($this->input->get('q'));
if(strlen($q)>0)
{
$config['enable_query_strings']=TRUE;
$getData = array('q'=>$q);
$config['base_url'] = base_url().'admin/Product/search/';
$config['suffix'] = '?'.http_build_query($getData,'',"&");
$config['first_url'] = $config['base_url'].'?q='.$q;
$config["per_page"] = 10;
$config['use_page_numbers'] = TRUE;
$total_row = $this->Prod_model->search_record_count($q);
$config['total_rows']=$total_row;
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = 'Next >';
$config['prev_link'] = '< Previous';
if($this->uri->segment(3))
{
$page = $this->uri->segment(3);
}
else
{
$page = 1;
}
$result['search'] = $this->Prod_model->search($q,$config["per_page"],$page);
if(empty($result['search']))
{
echo "no data found";die;
}
else
{
$this->pagination->initialize($config);
$str_links = $this->pagination->create_links();
$result["links"] = explode(' ',$str_links);
$id=$this->session->userdata('login_id');
$result['user']=$this->Home_model->user_details($id);
$this->template->load('prod_table',$result);
}
}
else
{
echo "empty string";die;
}
}
else
{
redirect(base_url()."admin/");
}
}

CodeIgniter Pagination, possible routing issue?

I'm trying to learn CodeIgniter and I'm having trouble with the pagination. I'm a complete newbie so I apologise if I've missed anything.
The pagination displays on my views fine, generates everything it should, but the pages give me a 404. I suspect it might have something to do with the routes or the uri_segment (though I've changed it to a whole bunch of numbers and nothing did the trick), but I'm not sure.
The URLs each page generates are /music3/music/20, /music3/music/40, etc.
Let me know if you need anything I haven't included.
Controller:
$config['base_url'] = 'http://moefoster.com/music3/music/';
$config['total_rows'] = $this->db->count_all('Music');
$config['per_page'] = '20';
$config['num_links'] = '5';
$config['uri_segment'] = '2';
$this->pagination->initialize($config);
$data['music'] = $this->music_model->get_music($config['per_page'], $config['uri_segment']);
Model:
public function get_music($num = 20, $offset = 0, $slug = FALSE) {
if ($slug === FALSE) {
return $this->db->select('*')->from('Music')->limit($num, $offset)->order_by('Release', 'desc')->get()->result_array();
}
$query = $this->db->get_where('Music', $num, $offset, array('Track' => $slug));
return $query->row_array();
}
Routes:
$route['music'] = 'music';
$route['default_controller'] = "music";
$route['(:any)'] = 'pages/view/$1';
you use standard pagination :/ nevermind, pagination generated like this:
class / function / pagination num
URL BASE:
$config['base_url'] = 'http://moefoster.com/music/';
ROUTES:
$route['music'] = 'music';
$route['music/(:num)'] = 'music/$1';
$route['default_controller'] = "music";
$route['(:any)'] = 'pages/view/$1';
but I use in backend, \libraries\My_Pagination.php
<?php
if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Pagination extends CI_Pagination
{
var $offset = 0;
var $pagination_selector = 'page';
var $index_page;
function MY_Pagination ()
{
parent::__construct();
log_message('debug', "MY_Pagination Class Initialized");
$this->index_page = config_item('index_page') != '' ? config_item('index_page') . '/' : '';
$this->_set_pagination_offset();
}
function _set_pagination_offset ()
{
$CI = & get_instance();
if (strstr($CI->uri->uri_string(), $this->pagination_selector)) {
$segments = $CI->uri->segment_array();
foreach ($segments as $key => $value) {
if ($value == $this->pagination_selector) {
$this->offset = $CI->uri->segment($key + 1);
$this->uri_segment = $key + 1;
$uri = $CI->uri->uri_string();
$pos = strpos($uri, $this->pagination_selector);
$this->base_url = '/'.$this->index_page . substr($uri, 0, $pos + strlen($this->pagination_selector.'/'));
}
}
}
else {
$this->offset = 0;
$this->uri_segment = 0;
$this->base_url = '/'.$this->index_page . $CI->uri->uri_string() . '/' . $this->pagination_selector.'/';
}
}
}
Example controller
function somefunction($somevariable){
$config['total_rows'] = Model_Admin::getCountClankyCategory($somevariable);
$config['per_page'] = 25;
$config['cur_tag_open'] = '#START SOME HTML#';
$config['cur_tag_close'] = '#END SOME HTML#';
$config['full_tag_open'] = '#START SOME HTML PAGINATION#';
$config['full_tag_close'] = '#END SOME HTML PAGINATION#';
$this->pagination->initialize($config);
$data['content'] = Model_Admin::getAllClankyCategory($somevariable,$config['per_page'],$this->pagination->offset);
.....
}
some example model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_Admin extends CI_Model {
private static $db;
function __construct()
{
parent::__construct();
self::$db = &get_instance()->db;
}
static function getAllClankyCategory($cat,$num,$offset) {
self::$db->where('#MYTYPE#',$cat);
return self::$db->get('#SOMETABLE#',$num,$offset)->result_array();
}
static function getCountClankyCategory($cat) {
return self::$db->count_all_results('#SOMETABLE#');
}
then if u use "some hard code routing", routes like, other u use without these routes
$route['admin/articles/cat/(:any)'] = "admin/cat/$1";
$route['admin/articles/cat/(:any)/(:num)'] = "admin/cat/$1/$2";
You can check one my previous answers on Pagination which explains very well how to do pagination and how to take care urls perfectly.....

Multiple views in codeigniter

I am working on a codeigniter site, in which a page is built using multiple views, I have come to a point where I need to work with a variable that is being set in another view is it possible to access it from another view?
This is code I have
Controller:
public function index() {
// $this->output->enable_profiler(TRUE);
$data = array();
if($query = $this->category_model->get_all_online()) {
$data['main_menu'] = $query;
}
$this->load->model('image_model');
/*
* Sort out the users backgrounds, basically do a check to see if there is a 'special' background
* if there is not a 'special' background then IF the user is logged in and has a background of there
* own show that one, if not show a generic one, if they are not logged in show a bang one
*/
$image = array();
if ($query = $this->image_model->get_special_backgrounds()) {
$image['special'] = $query;
} elseif(!isset($image['special']) && !isset($this->session->userdata['user_id'])) {
if($query = $this->image_model->get_mysite_background()) {
$image['generic'] = $query;
}
}
if(isset($this->session->userdata['user_id'])) {
if($query = $this->image_model->get_user_backgrounds($this->session->userdata['user_id'])) {
$image['user_background'] = $query;
}
}
$data = array_merge($data, $image);
$this->load->view('home/main_page.php', array_merge($data, $image));
}
Model:
public function get_mysite_background() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('users_user_group_group_id', 1);
$this->db->where('is_special', 0);
$query = $this->db->get();
return $query->result_array();
}
public function get_special_backgrounds() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('is_special', 1);
$query = $this->db->get();
return $query->result_array();
}
public function get_user_backgrounds($user_id) {
$this->db->select('*');
$this->db->from('background');
$this->db->where('users_user_id', $user_id);
$this->db->where('is_special', 0);
$query = $this->db->get();
return $query->result_array();
}
The Views in Question: Firstly where the variable is getting set,
</div>
<div id="background-select">
<?php
$count = 0;
if(isset($special)) {
foreach ($special as $row) {
$count ++;
print '<div class="select">';
print "<a href='index.php/home/category/".$row['background_id']."'>$count</a>";
print '</div>';
if($count = 1) {
$background = $row['background_name'];
}
}
}
if(isset($generic)) {
foreach ($generic as $row) {
$count ++;
print '<div class="select">';
print "<a href='index.php/home/category/".$row['background_id']."'>$count</a>";
print '</div>';
if($count = 1) {
$background = $row['background_name'];
}
}
}
if(isset($user_background)) {
foreach ($user_background as $row) {
$count ++;
print '<div class="select">';
print "<a href='index.php/home/category/".$row['background_id']."'>$count</a>";
print '</div>';
if($count = 1) {
$background = $row['background_name'];
}
}
}
?>
And where I want to use the variable:
<body>
<div id="wrapper" style=<?php echo"background:url(/media/uploads/backgrounds/".$background.");";?>>
The variable I looking to use $background
You can use the following helper class to transfer the values from one view to another:
class VarStore {
private static $values = array();
public static function get($key, $default = NULL) {
return (isset(self::$values[$key])? self::$values[$key] : $default);
}
public static function set($key, $value) {
self::$values[$key] = $value;
}
}
Call VarStore::set('background', $background); in the first view and $background = VarStore::get('background'); in the second.
Most of the problems in programming are conceptual and of understanding... The point is a View is to VIEW the data and not calculate it. calculations are carried out in models whose functions can be called by multiple modules when required. So better is before a view is called work-out all the data it has to display and use the view for VIEWING only not callucations... I hope this change of paradigm will help

Categories