How to run a query in model and load in the controller? - php

I was doing a query in the controller but it came to my attention that I should do it in the model.
This is the code I have in the controller
$this->db->where('page', 'your-secret-skill');
$this->data['articles'] = $this->article_m->get();
and this is the get method I have in the core model:
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
How would I go about this and do the query in the articles model and loading it with the controller?

You should inherit the CI_Model with the Articles model and in it you can write your query as:
class Articles_m extends CI_Model
{
function __construct()
{
parent::__construct();
$this->table_name = 'articles';
}
public function get()
{
$this->db->where('page', 'your-secret-skill');
$query = $this->db->get($this->table_name);
return $query->result();
}
}
and then in your controller:
$this->data['articles'] = $this->article_m->get();

Remove this line from the controller first:
$this->db->where('page', 'your-secret-skill');
Instead send your-secret-skill as a parameter to your model function:
$where = array( 'page', 'your-secret-skill' );
$this->data['articles'] = $this->article_m->get('','',$where);
In your model:
public function get($id = NULL, $single = FALSE, $where = array){
if(isset($where) && is_array($where)){
$this->db->where($where);
}
}

Related

Use session in static method (cakephp 4 and 3.6+)

If I try this is a class with static methods:
public static function chkLog($role)
{
$userrole = $this->getRequest()->getSession()->read('userrole');
return $userrole;
/// more code
Even tried:
public static function chkLog($role)
{
$userrole = Session::read('userrole');
return $userrole;
/// more code
In laravel I can:
public static function userRole($role = null)
{
$userrole = Auth::user()->role;
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return $role;
}
return false;
}
usage
public function scopegetPets($query, $petsearch = '')
{
$petsearch = $petsearch . "%";
$query = Pet::where('petname', 'like', $petsearch);
if (ChkAuth::userRole('admin') === false) {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid);
}
$results = $query->orderBy('petname', 'asc')->paginate(5);
return $results;
}
But in cakephp to call statically I had to write this:
public static function __callStatic($method, $params)
{
$instance = ChkAuth::class;
$c = new $instance;
return $c->$method(...array_values($params));
}
In order to call this:
public function userRole($role = null)
{
$userrole = $this->getRequest()->getSession()->read('userrole');
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return $role;
}
return false;
// more
And usage:
public function getPets($offset = "", $rowsperpage = "", $petsearch = "")
{
$pagingQuery = "LIMIT {$offset}, {$rowsperpage}";
$petsearch = $petsearch . "%";
if (Auth::chkRole('admin') === true) {
return DB::select("SELECT * FROM " . PREFIX . "pets " . $pagingQuery);
}
$authid = Auth::authId();
return DB::select("SELECT * FROM " . PREFIX . "pets WHERE ownerid = :authid " . $pagingQuery, ["authid" => $authid]);
}
So basically I am trying to figure out how to use session in cake php inside a static method.
Note the __callStatic works, but as a work a round.
CakePHP's Router class includes a static function to return the request object. The request object includes a function to return the session. So:
Router::getRequest()->session()
or, as of version 3.5:
Router::getRequest()->getSession()

Handing the ID from the database to the URL - CodeIgniter

I am starting my game with CodeIgniter and I have a problem - I would like to download the ID - of the product from the database so that it will be passed to the URL address:
Example address:
http://localhost/crm-SEO/api/admin/domains/{{ID in database}}/notes
When I have other methods like:
domains/GET/6
domains/update/6
Everything works fine for me, but I can not grasp it that I have domains/{{ID}}/
My code i models:
public function get( $id = false)
{
if ( $id == false ) {
$q = $this->db->get('domains');
$q = $q->result();
}
else{
$this->db->where('id', $id);
$q = $this->db->get('domains');
$q = $q->row();
}
return $q;
}
public function update($domain)
{
$this->db->where('id', $domain['id'] );
$this->db->update('domains', $domain);
}
public function create($domain)
{
$this->db->insert('domains', $domain);
}
public function delete($domain)
{
$this->db->where('id', $domain['id'] );
$this->db->delete('domains');
}
My code in controller:
public function __construct()
{
parent::__construct();
$post = file_get_contents('php://input');
$_POST = json_decode($post,true);
$this->load->model('admin/domains_model');
}
public function get($id = false)
{
$result = $this->domains_model->get($id);
echo '{"records":' . json_encode( $result ) . '}';
}
public function update()
{
$domain = $this->input->post('domain');
$this->domains_model->update($domain);
}
public function create()
{
$domain = $this->input->post('domain');
$this->domains_model->create($domain);
}
public function delete()
{
$domain = $this->input->post('domain');
$this->domains_model->delete($domain);
}

run multiple select quires in one page using codeigniter

Hello any one can tell that how to load two function from model class in controller one method. I want to run multiple select quires in one page using codeigniter:
Controller
public function property_detail( $id )
{
$this->load->model('insertmodel');
$select1 = $this->insertmodel->find($id);
$select2 = $this->insertmodel->detail_list();
$data = array();
$this->load->view('home/property_detail', ['select1'=>$select1], ['select2'=>$select2]);
//$this->load->view('home/property_detail', ['select2'=>$select2]);
}
Model
public function find( $id )
{
$query = $this->db->from('article')->where(['id'=> $id])->get();
if( $query->num_rows() )
return $query->row();
return false;
}
public function detail_list(){
$query1 = $this->db->query("select * from article");
return $query1->result();
}
In Controller
public function property_detail( $id )
{
$this->load->model('insertmodel');
$data['select1'] = $this->insertmodel->find($id);
$data['select2'] = $this->insertmodel->detail_list();
$this->load->view('home/property_detail', $data);
}
In Model
public function find($id)
{
$query = $this->db->get_where('article', array('id' => $id), 0, 0)->get();
if( $query->num_rows() > 0 )
{
$result = $query->result_array();
return $result;
}
else
{
return false;
}
}
public function detail_list()
{
$query1 = $this->db->query("select * from article");
$result = $query1->result_array();
return $result;
}
In View
foreach ($select2 as $item) {
# your foreach lop goes here
}
As well check empty() before passing it to the foreach loop
As an alternative to #Rijin's useful answer newMethod() can make calls to the existing model methods. This might be useful if you don't want to break the interface already created for the model because you are using find($id) and detail_list() in other code.
Model:
public function find($id)
{
$query = $this->db->from('article')->where(['id' => $id])->get();
if($query->num_rows())
return $query->row();
return false;
}
public function detail_list()
{
$query1 = $this->db->query("select * from article");
return $query1->result();
}
public function newMethod($id)
{
$result['select1'] = $this->find($id);
if($result['select1'] !== FALSE)
{
$result['select2'] = $this->detail_list();
return $result;
}
return FALSE;
}
Controller:
public function property_detail($id)
{
$this->load->model('insertmodel');
$data = $this->insertmodel->newMethod($id);
$this->load->view('home/property_detail', $data);
}
Model :
public function find( $id )
{
$query = $this->db->from('article')->where(['id'=> $id])->get();
if( $query->num_rows() )
return $query->row();
return false;
}
public function detail_list()
{
$query1 = $this->db->query("select * from article");
return $query1->result();
}
Controller :
public function property_detail( $id )
{
$this->load->model('insertmodel');
$data['select1'] = $this->insertmodel->newMethod($id);
$data['select2'] = $this->insertmodel->detail_list();
$this->load->view('home/property_detail', $data);
}

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);
}

Codeigniter Database error 1364 MY_model [duplicate]

This question already has answers here:
MySql Error: 1364 Field 'display_name' doesn't have default value
(7 answers)
Closed 8 years ago.
Hi i am having a problem with codeiginiter i am getting this error when i create a new page on my codeigniter cms page.
A Database Error Occurred
Error Number: 1364
Field 'order' doesn't have a default value
INSERT INTO pages (title, slug, body, parent_id) VALUES
('Content', 'content', '
Page content
', 0) Filename: /Applications/AMPPS/www/application/core/MY_Model.php
Line Number: 62
My code for MY_Model.
<?php
class MY_Model extends CI_Model {
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct() {
parent::__construct();
}
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE){
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL){
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id){
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
The error message is self explanatory. You're not supplying a value for order, it is required, and there is no default value.
You can do a few things..
Change your schema to provide a default for that field
Make it nullable
Provide a value for it in your query

Categories