Getting an empty array in codeigniter project - php

In the code below,I'm getting an empty array for the third if-else statement. What I'm trying is that get a range of date from user and showing the data from the table accordingly. My first if-else statement is returning desired results but the second one is returning empty array.
Controller:
public function bookings()
{
if($this->userlib->isLoggedIn())
{
if($this->userlib->isAdmin())
{
$this->load->view('admin_search_booking');
$date_posted_from = $this->input->post('date_posted_from');
$date_posted_till = $this->input->post('date_posted_till');
$date_posted_on = $this->input->post('date_posted_on');
if(is_null($date_posted_from) && is_null($date_posted_till) && is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->total_trail();
var_dump($total_trails);
}
elseif(!is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->filter_on_date($date_posted_on);
var_dump($total_trails);
}
elseif(!is_null($date_posted_from) && !is_null($date_posted_till))
{
$total_trails = $this->admin_panel_model->filter_by_date($date_posted_from, $date_posted_till);
var_dump($total_trails);
}
}
}
else
{
echo "User not Logged In";
}
}
Model filter_by_date :-
public function filter_by_date($date_posted_from, $date_posted_till)
{
$query = $this->db->select('*')
->where('date >=', $date_posted_from)
->where('date <=', $date_posted_till)
->get($this->search);
return $query->result();
}
isLoggedIn :-
public function isLoggedIn()
{
if($this->ci->session->email)
return true;
else
return false;
}

Change your model function like this
public function filter_by_date($date_posted_from="", $date_posted_till="")
{
$query = $this->db->select('*');
if($date_posted_from)
$this->db->where('date >=', $date_posted_from);
if($date_posted_till)
$this->db->where('date <=', $date_posted_till);
$this->db->get($this->search);
return $query->result();
}

//This may help you put your table name in your select statement and update where clause
public function filter_by_date($date_posted_from, $date_posted_till){
$date_posted_from='2015-10-10';
$date_posted_till='2015-10-16';
$query = $this->db->select('*')->from('Your_Table_Name')
->where("date >= '".$date_posted_from."'")
->where("date <= '".$date_posted_till."'")
->get($this->search);
return $query->result();
}

Use $this->db->last_query(); after filter_by_date() and check what query is actually being executed. And also make sure there are records exists in the date range you are searching for.
Or simply use straight forward query,
$Q = $this->db->query("select * from table_name where date >='".$date_posted_from."' and date <='".$date_posted_to."'");
return $Q->result_array();

Related

What causes this failure to get the data from the next row in a MySQL table, with Codeigniter 3?

I am working on an online newspaper/blogging application with CodeIgniter 3.1.8 and Bootstrap 4.
At the bottom of the single post view, I want to add a link to the next post (as well as one to the previous post). For this, I need to get the data (slug, title, etc), of the next post (row in the posts table).
For this purpose, I have added this method to my Posts_model model:
/* Next post */
public function get_next_post($slug) {
$query = $this->db->get_where('posts', array('slug' => $slug));
if ($query->num_rows() > 0) {
$data = $query->next_row();
return $data;
}
}
In the controller I have:
public function post($slug) {
//more code
$data['post'] = $this->Posts_model->get_post($slug);
$data['next_post'] = $this->Posts_model->get_next_post($slug);
print_r($data['next_post']);
//more code
}
EDIT: In the Posts_model, I now have:
/* Next post */
public function get_next_post($slug) {
$query = $this->db->get('posts');
$row_index = 6;
$data = $query->row_array($row_index);
if ($query->num_rows() > 0) {
$data = $query->next_row();
return $data;
}
}
/* Prev post */
public function get_prev_post($slug) {
$query = $this->db->get('posts');
$row_index = 6;
$data = $query->row_array($row_index);
if ($query->num_rows() > 0) {
$data = $query->previous_row();
return $data;
}
}
That means that if I could get the current post's index by slug, I could replace this hardcoded index of the 7th post - $row_index = 6 - and the problem would be solved.
How do I do that?
// Your_model.php
...
public function getPost($slug) {
$this->db->where('slug', $slug);
return $this->db->get('posts_table')->row_array();
}
public function getPrevPost($currentPostId) {
$this->db->where('id <', $currentPostId);
$this->db->order_by('id', 'desc');
$this->db->limit(1);
return $this->db->get('posts_table')->row_array();
}
public function getNextPost($currentPostId) {
$this->db->where('id >', $currentPostId);
$this->db->limit(1);
return $this->db->get('posts_table')->row_array();
}
// Yourcontroller.php
...
public function getPost($slug) {
$post = $this->your_model->getPost($slug);
$data = [
'thePost' => $post,
...
'prevPost' => $this->your_model->getPrevPost($post['id']),
'nextPost' => $this->your_model->getNextPost($post['id']),
...
];
...
}
EDIT: this post answers the original question. In the meantime below code was used in an edit by OP.
you need to return a result of your query: $data = $query->row_array();
And get_where() is limiting the record-set to one record, hence there is no next record. You need to return the complete record-set with $this->db->get('posts'). In case you know the row_number (e.g.: 5) of the row containing $slug, you can point to it. The next_row shown, is row number 6.
public function get_next_post($slug) {
$query = $this->db->get('posts'); // querying the whole data-set
$data = $query->row_array(5); // the missing line
if ($query->num_rows() > 0) {
$data = $query->next_row();
return $data;
}
}
now you should get your next row (if exists), see Result Rows

How to get users list in codeigniter?

I am trying to get list of users from Users table in codeigniter. My problem is that if am using following code than try to print out the result, it's giving me blank array while printing query using last_query() function and running this query in phpmyadmin is giving correct result.
My code in model
$data = $this->db->select('u.*')
->from('users u')
->join('users_groups ug','ug.user_id = u.id')
->join('groups g','g.id = ug.group_id')
->where('g.id',7)
->get()
->result();
this code is giving me blank array then what i did is print the query using following code
echo $this->db->last_query();
and this is what query was
SELECT `u`.* FROM `users` `u` JOIN `users_groups` `ug` ON `ug`.`user_id` = `u`.`id` JOIN `groups` `g` ON `g`.`id` = `ug`.`group_id` WHERE `g`.`id` = 7
which is working fine. but i am trying to print the data using print_r($data)
is giving me blank array.
Can anyone tell me what can be the issue ?
edited
My full model code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Technician_model extends CI_Model {
public function _consruct(){
parent::_construct();
}
function getData(){
$data = $this->db->select('u.*')
->from('users u')
->join('users_groups ug','ug.user_id = u.id')
->join('groups g','g.id = ug.group_id')
->where('g.id',7)
->get()
->result();
return $data;
}
function getRecord($user_id){
$record = $this->db->get_where('users',array('id'=>$user_id))->row();
echo '<pre>';
print_r($record);
exit;
return $record;
}
function addModel($data){
if($this->db->insert('users',$data)){
return $this->db->insert_id();
}
else{
return FALSE;
}
}
function editModel($data,$user_id){
$this->db->where('id',$user_id);
if($this->db->update('users',$data)){
return true;
}
else{
return false;
}
}
function deleteModel($user_id){
$this->db->where('id', $user_id);
if($this->db->delete('users')){
return true;
}
else{
return FALSE;
}
}
}
?>
You may try this simple way to join table. you may try this and can
change fields name table name and method according to your
require.
public function getUser() {
$this->db->select('users');
$this->db->from('Users');
$this->db->where('users_groups.user_id',1);
$this->db->join('users_groups', 'users.id = users_groups.user_id');
$query = $this->db->get();
$result = $query->result_array();
var_dump($result); // display data in array();
return $result;
}
Actually, at the end of 2 hrs of the journey, I found that I forgot to configure new database.
All the answers were correct in this case.

Fatal error: Can't use function return value in write context in Codeigniter

This is the function I am using in my model
public function user_birthday() {
$this->db->select('birth_day')
->from('informations')
->where(DATE_FORMAT(FROM_UNIXTIME('birth_day'), '%m-%d') = DATE_FORMAT(NOW(), '%m-%d'));
$q = $this->db->get();
return $q->result();
}
function in controller like $this->data['user'] = $this->users_m->user_birthday(); that way
and code in the view is
if (!empty($user)):
echo $user;
else:
echo "No dob found";
endif;
This is one of those circumstances where Query Builder is more trouble that it is worth. Try this
$q= $this->db->query("SELECT birth_day FROM informations WHERE DATE_FORMAT(birth_day, '%m-%d') = DATE_FORMAT(NOW(), '%m-%d')");
//return empty array if not records found
return $q->num_rows() > 0 ? $q->result() : [];
If you really, really, really want to use Query Builder then this
$q = $this->db
->select('birth_day')
->where("DATE_FORMAT(birth_day, '%m-%d')=", "DATE_FORMAT(NOW(), '%m-%d')", FALSE)
->get('informations');
return $q->num_rows() > 0 ? $q->result() : [];

Codeigniter not getting data though available in mysql database

I have a model which fetch the data from database is below
public function counselor() {
$inst_id = $this->session->userdata('user_id');
$submission_key=$this->session->userdata('submission_key');
$query = $this->db->query("SELECT * FROM counselor where USER_ID = $inst_id AND submission_key= $submission_key");
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}
}
I have tested the $inst_id and $submission_key by printing it and its set.
$inst_id=2 and $submission_key=2016-8 .BUT though I have one record in database with those two field set its not returning the data. What is the case. I have tried with codeigniter get() and where() method too. Still not giving me the result.
Just write your query using active record function. It will help you in escaping string
$this->db->select('*',FALSE);
$this->db->where('USER_ID',$inst_id);
$this->db->where('submission_key',$submission_key);
$query=$this->db->get('counselor');
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}

Redirecting not working in codeigniter

So here's what I want to do. I want to check if the userid in segment(3) exist or else it will redirect somewhere instead of still loading the view with an error.
Here's the example url
http://localhost/ems/edit_user/edit_user_main/1001
Now if I try to edit the userid in segment(3) and intentionally put an invalid userid, it still loads the view and i don't know why
Here's my function
public function edit_user_main(){
$id = $this->uri->segment(3);
$check = $this->get_data->check_if_exist($id);
if($check) {
$data['title'] = 'Edit User';
$data['id'] = $this->session->userdata('usertoedit');
$this->load->model('accounts/get_data');
$item = $this->get_data->get_user($id);
$data['user'] = $item[0];
$data['main_content'] = 'edit_user/edit_user_main';
$this->load->view('includes/template', $data);
} else {
redirect('admin/adminuser');
}
}
Here's the model
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query) {
return TRUE;
} else {
return FALSE;
}
}
There is no problem with the fetching of data.
The problem is even if the userid doesn't exist, the view is still loading but with an error coz there's no data for that userID. It's not redirecting,
I tried using print_r and it working fine, the value of the $check is 1 when there's a valid userID.
Hope someone can help me with this. Thank you
With your function it will always return true because the statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always execute,So you need to check query is returning any result row or not with the statement
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
Try this..
With the function it will always return true because the following statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always be execute, So need to check query is returning any result row or not
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
And load heper as:-
$this->load->helper('url');
before the redirection

Categories