codeigniter 3: does my code follow MVC rule - php

I am new to codeigniter 3 and try to convert my PHP project to MVC by this Framework
Controller file
class home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('frontend/M_Headers');
}
public function index()
{
$data['slide_image'] = $this->M_Headers->get_all_slide();
$this->load->view('frontend/headers',$data);
}
}
Model file
class M_Headers extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_all_slide()
{
$query = $this->db->get('tbl_slide');
return $query->result();
}
}
View file
<div class="slider">
<ul class="rslides" id="slider">
<?php
if(count($slide_image) > 0)
{
foreach($slide_image as $value):
$get_image=$value->sl_image;
if($get_image != ''):
$image_properties = array(
'src' => 'assets/images/slide/'.$get_image,
'alt' => '',
);
?>
<li><?php echo img($image_properties); ?></li>
<?php else: ?>
<li>No Slide</li>
<?php
endif;
endforeach;
}
?>
</ul>
</div>
did am i right that loop result in View or should i do it in
Controller?
which query should i use between active record or bind (where id=?) or they had it own benefit in difference situation?

The loop in the view is correct. Because it is "view logic" (repeating li's) you can use into the view.
Your Model can be better. I personally like to use the model as a representation of the item from the database. Like this:
class M_Headers extends CI_Model
{
private var $tablename = "tbl_slide";
var $id;
var $sl_image;
public function __construct()
{
parent::__construct();
}
public function get_all_slide()
{
$slides = array();
$query = $this->db->get($this->tablename);
foreach($query->result() as $row)
{
$item = new self();
$item->id = $row->id;
$item->sl_image = $row->sl_image;
$slides[] = $item;
}
return $slides;
}
public function get_slide($id)
{
$this->db->where("id", $id);
$query = $this->db->get($this->tablename);
$results = $query->result();
if(isset($results[0]))
{
$row = $results[0];
$this->id = $row->id;
$this->sl_image = $row->sl_image;
return true;
}
return false;
}
}
You can even improve this to make a method that loads the row into the model:
class M_Headers extends CI_Model
{
private var $tablename = "tbl_slide";
var $id;
var $sl_image;
public function __construct()
{
parent::__construct();
}
private function load_with_record($row)
{
$this->id = $row->id;
$this->sl_image = $row->sl_image;
}
public function get_all_slide()
{
$slides = array();
$query = $this->db->get($this->tablename);
foreach($query->result() as $row)
{
$item = new self();
$item->load_with_row($row);
$slides[] = $item;
}
return $slides;
}
public function get_slide($id)
{
$this->db->where("id", $id);
$query = $this->db->get($this->tablename);
$results = $query->result();
if(isset($results[0]))
{
$row = $results[0];
$this->load_with_row($row);
return true;
}
return false;
}
}

Related

Unable to update or delete rows in database using codeigniter

I am new to code-igniter, and I am facing unknown issues in updation and deletion of rows in my database. My code for Controller is :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Nhome extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->Model('N_model');
$data['r'] = $this->N_model->getdata();
$this->load->view('Homeview',$data);
}
public function edit()
{
$id = $this->input->get('id');
$this->load->Model('N_model');
$data['s'] = $this->N_model->editdata();
$this->load->view('Neditview',$data);
}
public function loadEdit()
{
$id = $this->input->get('id');
$this->load->view('Neditview');
}
public function insertdata()
{
$eID = isset($_POST['Id'])?$_POST['Id']:'';
$arr['Name'] = $_POST['Name'];
$arr['Gender'] = $_POST['Gender'];
$arr['Email'] = $_POST['Email'];
$this->load->Model('N_model');
$res = $this->N_model->updatedata($arr , $eID);
if($res){
header('location:'.base_url()."index.php/Nhome/".$this->index());
}
}
public function delete(){
$this->load->Model('N_model');
$id = $this->input->get('Id');
$this->N_model->deletedata($id);
$this->index();
}
}
and my code for model is :
<?php
class N_Model extends CI_Model{
public $Id;
public $Name;
public $Gender;
public $Email;
public function __construct()
{
parent::__construct();
}
public function getdata()
{
$va = $this->db->get('newprac');
$res = $va->result();
return $res;
}
public function editdata($id)
{
$vr = $this->db->where('Id',$id);
return $vr;
}
public function updatedata($data , $id){
$this->db->where('newprac.Id',$id);
$res = $this->db->update('newprac', $data);
return $res;
}
public function deletedata($id)
{
$this->db->where('newprac.id',$id);
$this->db->delete('newprac');
if($this->db->affected_rows()>0)
{
return true;
}
else { return false; }
}
}
Change
$this->db->where('newprac.id',$id)
to
$this->db->where('id',$id);
Simplify your code to:
$this->db->where('id',$id)->update('newprac', $data);
Replace your controller by this code. Becuase I think you passing data as a post method so you should use post when you retrieve data.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Nhome extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->Model('N_model');
$data['r'] = $this->N_model->getdata();
$this->load->view('Homeview',$data);
}
public function edit()
{
$id = $this->input->post('id');
$this->load->Model('N_model');
$data['s'] = $this->N_model->editdata();
$this->load->view('Neditview',$data);
}
public function loadEdit()
{
$id = $this->input->post('id');
$this->load->view('Neditview');
}
public function insertdata()
{
$eID = isset($_POST['Id'])?$_POST['Id']:'';
$arr['Name'] = $_POST['Name'];
$arr['Gender'] = $_POST['Gender'];
$arr['Email'] = $_POST['Email'];
$this->load->Model('N_model');
$res = $this->N_model->updatedata($arr , $eID);
if($res){
header('location:'.base_url()."index.php/Nhome/".$this->index());
}
}
public function delete(){
$this->load->Model('N_model');
$id = $this->input->post('Id');
$this->N_model->deletedata($id);
$this->index();
}
}
Did you try to debug using Chrome debugger. You might get the exact error in debugger. I suggest you to try once let me know the error name.

How to get everything outside the database with foreach and class

I have a problem. I want some data out my database.
I have two page's a categorie.php here I want that he shows everything out the database. And I have a second page. Here are my classes. I have trying a foreach on the categorie.php but if I do that, than shows he 1 thing out the database 4 times the same and not the another data.
Below you can see my code.
I hope that you can help me.
Thank you.
This is my categorie.php
<?php
require_once '../app/functions/second.php';
require_once '../app/db/dbpassword.php';
require_once 'include/head.php';
if (isset($_GET['categorie']) && !empty($_GET['categorie'])) {
$id = $_GET['categorie'];
$dbh = new PDO("mysql:host=$host; dbname=$dbname;", $usernamedb,
$passworddb);
$cate = new Categorie($dbh);
$cate->loadCate($id);
// $page->loadId($id);
$categorie = $cate->getCategorie();
$titel = ucwords($categorie);
?>
<h2 class="center_h2"><?= $titel ?></h2>
<?php foreach ($cate as $key) {
$titelart = $cate->getTitel();
$beschrijving = $cate->getBeschrijving();
$plaatje = $cate->getImage();
$id = $cate->getId();
var_dump($titelart);
} ?>
<?php
} else {
echo "Dit bericht is verwijderd of is verplaats.";
}
require_once 'include/footer.php';
?>
This is my class page
<?php
class Categorie {
protected $dbh;
public function __construct($new_dbh){
$this->dbh = $new_dbh;
}
public function loadCate($cate){
$query = $this->dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$this->id = $row->id;
$this->categorie = $row->categorie;
$this->titel = $row->titel;
$this->beschrijving = $row->beschrijving;
$this->plaatje = $row->plaatje;
}
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitel(){
return $this->titel;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
?>
Ok so you have a problem with the use of your class. In the while after your SQL request, you apply the value the instance variable like $this->id = $row->id; but this variable will be rewrite with the next row value.
Use a static function for your SQL request and return an array of Categorie like that :
class Categorie {
protected $id, $categorie, $title, $beschrijving, $plaatje;
public function __construct($id, $categorie, $title, $beschrijving, $plaatje){
$this->id = $id;
$this->categorie = $categorie;
$this->title = $title;
$this->beschrijving = $beschrijving;
$this->plaatje = $plaatje;
}
public static function loadCate($dbh, $cate){
$query = $dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
$res = array();
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$res[] = new Categorie($row->id, $row->categorie, $row->titel, $row->beschrijving, $row->plaatje);
}
return $res;
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitle(){
return $this->title;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
And you can use it like that:
$categories = Categorie::loadCate($dbh, $id);
foreach($categories as $categorie){
var_dump($categorie->getTitle());
}

Load multiple models within same function of controller

I have two functions in my model as
class Jobseeker_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function result_getall($id)
{
$this->db->select('*');
$this->db->from('tbl_jobseeker');
$this->db->where('tbl_jobseeker.User_id',$id);
$this->db->join('tbl_work_exp', 'tbl_jobseeker.User_id = tbl_work_exp.User_id','left');
$query = $this->db->get();
return $query->row();
}
public function select($id)
{
$this->db->select('*');
$this->db->from('tbl_qualification');
$this->db->where('tbl_qualification.User_id',$id);
$query = $this->db->get();
return $query->result();
}
}
And in my controller I have a function as
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$res['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data,$res);
}
It is not possible to display the view page.. I could pass two variables into my view page.right?
You can pass your any number of variables/arrays using a single array.
In Controller:
public function display() {
$id = $this->session->userdata('user_id');
$data['var1'] = $this->jobseeker_model->result_getall($id);
$data['var2'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
In View:
`$var1` and `$var2` will be available.
You can pass your two variable using single srray
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$data['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
Views
foreach($a as $data){
// your code
}
echo $row->column_name;
Try this
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$data['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}

Class with a db query, extending, functions and views. Am I doing it right way?

I have just a little progress in practicing. Most of my code works but I am not sure if I do things the right way?
Please, can you tell me if I do mistakes and correct me.
First, I create autoload functions:
function autoload_models($model) {
if (file_exists(MODELS_PATH . $model . '.php')) {
require_once MODELS_PATH . $model . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_models');
function autoload_controllers($controller) {
if (file_exists(CONTROLLERS_PATH . $controller . '.php')) {
require_once CONTROLLERS_PATH . $controller . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_controllers');
I have a class like this:
class Category {
public $db;
public $rows;
public $id;
public function build_category() {
global $db;
global $rows;
$db = new Database();
$db->query("SELECT * from categories");
$rows = $db->resultset();
}
public function category_items() {
global $db;
global $rows;
global $id;
$db = new Database();
$db->query("SELECT * from posts WHERE category_id = '$id'");
$rows = $db->resultset();
}
}
I extend with another class (still have some issues here. Nothing prints):
class Category_Items extends Category {
public $db;
public $rows;
public $id;
public function display_category_items() {
// Call the parent class function
parent::category_items();
global $rows;
global $id;
// Check if the page parameter is integer
if (ctype_digit($_GET['id'])) {
$id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
foreach ($rows as $row) {
print "test";
print $row['post_title']; // This does not work yet. Nothing prints
}
}
}
Class for building a menu with categories (Everything works here):
class Categories_Menu extends Category {
public $db;
public $rows;
public function build_category_menu() {
parent::build_category();
global $rows;
foreach ($rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
And finally instances:
$category_menu = new Categories_Menu();
$category_menu->build_category_menu();
$category_items = new Category_Items();
$category_items->display_category_items();
Thank you for your time and help!
Where do the global variables come from?
Anyway, you should get rid of them.
I guess your rows var does not get changed, after any interaction. Using globals also will not be relevant in extending classes.
Your public properties and globals mentioned, does no interact each other. Thus, the object members seems to be totally useless.
What I would suggest in simple schems would be
class Model {
protected $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
class Category extends Model {
public $_rows;
public $_id;
public function build_category() {
$this->_db->query("SELECT * from categories");
$this->_rows = $this->_db->resultset();
}
public function category_items() {
$this->_db->query("SELECT * from posts WHERE category_id = '{$this->_id}'");
$this->_rows = $this->_db->resultset(); // here you will overwrite $_rows ?
}
class Categories_Menu extends Category {
public $_rows;
public function build_category_menu() {
$this->build_category();
foreach ($this->_rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
class Category_Items extends Category {
public $_rows;
public $_id;
public function display_category_items() {
if (ctype_digit($_GET['id'])) { // just intval it, or use is_int?
$this->_id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
// You assign value to $_id, then call the function that requires it
$this->category_items();
foreach ($this->_rows as $row) {
print "test";
print $row['post_title'];
}
}
}

using codeigniter PHP Fatal error: Class 'MY_Model' not found

Now I am learning CodeIgniter_2.1.4 but I got a php error;
I have a my_model.php file in /data/www/application/core
<?php
class MY_Model extends CI_Model {
const DB_TABLE = 'abstract';
const DB_TABLE_PK = 'abstract';
private function insert() {
$this->db->insert($this::DB_TABLE, $this);
$this->{$this::DB_TABLE_PK} = $this->db->insert_id();
}
private function update() {
$this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK);
}
public function populate($row) {
foreach($row as $key => $value) {
$this->$key = $value;
}
}
public function load($id) {
$query = $this->db->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $id,
));
$this->populate($query->row());
}
public function delete(){
$this->db->delete($this::DB_TABLE, array(
$this::DB_TABLE_PK => $this->{$this::DB_TABLE_PK},
));
unset($this->{$this::DB_TABLE_PK});
}
public function save(){
if(isset($this->{$this::DB_TABLE_PK})) {
$this->update();
}
else {
$this->insert();
}
}
public function get($limit = 0, $offset = 0) {
if($limit) {
$query = $this->db->get($this::DB_TABE, $limit, $offset);
}
else {
$query = $this->db->get($this::DB_TABLE);
}
$ret_val = array();
$class = get_class($this);
foreach ($query->result() as $row) {
$model = new $class;
$model->populate($row);
$ret_val[$row->{$this::DB_TABLE_PK}] = $model;
}
return $ret_val;
}
}
and my domain model is :
<?php
class Publication extends MY_Model {
const DB_TABLE = 'publications';
const DB_TABLE_PK = 'publication_id';
public $publication_id;
public $publication_name;
}
well when I get model in my controller I got this php error:
PHP Fatal error: Class 'MY_Model' not found in /data/www/application/models/publication.php on line 3
I have tried two hours finding the reason but failed ):
I have a my_model.php file in /data/www/application/core
the my_model.php should be renamed to MY_Model.php.
It should be a case-sensitivity issue. Class names must have the first letter capitalized with the rest of the name lowercase.
in your publications.php have the following statement before the class declaration.
require_once "my_model.php";
the error is because you haven't included the definition of My_Model in your publications.php

Categories