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;
}
Related
I have 2 cases where i am fetching the entire data and total number of rows of a same table in codeigniter, I wish to know that is there a way through which i can fetch total number of rows, entire data and 3 latest inserted records from the same table through one code
Controller code for both cases is as given below (although i am applying it for each case seperately with different parameters)
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$data);
}
1) to fetch the entire data from a table in codeigniter
Model Code
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->result();
}
View Code
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
2) to fetch number of rows from a table in codeigniter
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->num_rows();
}
View Code
echo $instant_req;
You can make only one function that gives you the all data at once total number of rows, entire data and 3 latest inserted records
for example in the model
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$result=$query->result();
$num_rows=$query->num_rows();
$last_three_record=array_slice($result,-3,3,true);
return array("all_data"=>$result,"num_rows"=>$num_rows,"last_three"=>$last_three_record);
}
in controller dashboard function
public function dashboard()
{
$result = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$result);
}
in view
foreach ($all_data as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//latest three record
foreach ($last_three as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//total count
echo $num_rows;
Raw query may work here.
$resultSet = $this->db->query("select * from table_name");
$queryCount = count($resultSet );
Try this logic :
Model code :
public function getreq()
{
$this->db->where('status','pending');
$this->db->order_by('id', 'DESC'); //actual field name of id
$query=$this->db->get('instanthire');
return $query->result();
}
Controller Code :
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$data['total_record'] = count($data['instant_req']);
$this->load->view('admin/dashboard',$data);
}
View Code:
$i=0;
foreach ($instant_req as $perreq)
{
if($i<3){
echo $perreq->fullname;
echo "<br>";
}
$i++;
}
Echo 'Total record : '.$total_record;
Function
function getData($limit = 0){
//Create empty array
$data = [];
//Where clause
$this->db->where('status','pending');
//Order Data based on latest ID
$this->db->order_by('id', 'DESC');
if($limit != 0){
$this->db->limit($limit);
}
//Get the Data
$query = $this->db->get('instanthire');
$data['count'] = $query->num_rows();
$data['result'] = $query->result();
return $data;
}
Calls
//Last 3 Inserted
$data = getData(3);
//All Data
$data = getData();
CodeIgniter Database Documentation
Here is a simple solution that I can first think of but if you want me to maybe improve I can.
Just stick with your first code(Model) and in the view count how many items are iterated through.
$count = 0;
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
$count++;
}
echo $count;
Am I still missing something? just let me know
EDIT:
This is another solution, return an array
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$data['results'] = $query->result();
$data['count'] = $query->num_rows();
return $data
}
I'm not very confident and haven't really tried this but on top of my head I think it can work.
Model:
public function getreq()
{
$res = $this->db->order_by("<place column primary id>","desc")->get_where('instanthire',['status'=> 'pending']);
$latest_3 = [];
if(count($res)){
$i=1;
foreach($res as $r){
$latest_3[]=$r;
if($i == 3)
break;
$i++;
}
}
$arr = [
'latest_3' => $latest_3,
'count' => count($res),
'total_result' => $res,
];
return $arr;
}
Good Evening,
I got a problem with the last insert id function with active record codeigniter, it works fine in mysql. But when i try it on SQL Server, the result always return false. Please kindly take a look on my code:
function transactions_start($data) {
$this->db->insert($this->table, $data);
$id = $this->db->insert_id();
$q = $this->db->affected_rows();
if ($q > 0) {
return $id;
} else {
return FALSE;
}
}
this is the result of $this->db->last_query()
select ##IDENTITY as id
the var_dump() result always returning bool(false).
I'm developing this apps using MySQL and SQL Server, so i need to keep using the active record from codeigniter.
Any help would be great, thanks in advance!
The insert_id() function returns the id of last inserted row so you just check whether it is greater than 0 or not. Use it like
function transactions_start($data) {
$this->db->insert($this->table, $data);
$id = $this->db->insert_id();
if ($id > 0) {
return $id;
} else {
return FALSE;
}
}
Reference : https://ellislab.com/codeigniter/user-guide/database/helpers.html
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
I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole
I have 2 tables one keeps the log and the other one keeps the user name.
Table one(logs) has
ID|USERID|DATETIME|MESSAGE
Table two(users) has
ID|USERNAME|PASSWORD
In codeigniter model I have
function getRlog(){
$this->db->limit(100);
$this->db->order_by("id","desc");
$this->db->where('type', "reservation");
$q = $this->db->get('logs');
if($q->num_rows() > 0) {
foreach($q->result() as $row){
$data[] = $row;
}
return $data;
}
}
In the controller I have...
function log(){
if (!$this->ion_auth->is_admin())
{
$this->session->set_flashdata('message', 'You must be an admin to view this page');
redirect('auth/login');
} else {
$data ['user'] = $this->ion_auth->get_user();
$this->load->model('Logs_model');
$data['logs'] = $this->Logs_model->getRlog();
$this->load->view('database/log', $data);
}
}
I want to get the username from the users table based on the id from the logs table. Should I create a foreign key? and If I do how do I get the username?
you might do it this way in your model
function getRlog(){
$this->db->limit(100);
$this->db->order_by("id","desc");
$this->db->where('type', "reservation");
$q = $this->db->get('logs');
if($q->num_rows() > 0) {
$data = array(); //create new data array to be returned
foreach($q->result() as $row){
$row->user = $this->ion_auth->get_user($row->userid); //create new user property that contains user object
$data[] = $row; //append to new data array with appended user property
}
return $data;
}
else {
return false; //if no results make sure you return something, either false or empty array depending on your needs.
}
}
This way you can access the entire user object from your log results returned from the model like so, assuming your controller stays the same.
View
foreach($logs as $log) {
echo $log->user->username;
}
or even...
foreach($logs as $log) {
echo $log->user->email; //etc...
}