converting database result into array in codeigniter - php

I am new to codeigniter and I am trying to make a login authentication system with the role of admin, moderator, and user.
My problem is that I am trying to set a condition on 'role' which is a column in database. But I don't know how to use and compare the value of column role.
I wrote the following code but I am getting error:
[Severity: Error Message: Call to a member function result_array() on array]
My code is:
<?php
// step no 4 create a new controller where form post after submission.
class verify extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->model('user');
}
function login(){
//step no 5 create a new method in verify controller
$username = $this->input->post('username');
$userpass = $this->input->post('password');
//step 9 take value back in answer variable from model and print message
$answer = $this->user->usergetdata($username,$userpass,'admin');
$data = $answer->result_array();
if($answer){
if($data[0]['role']=='admin'){
redirect('admin_page');
}
}else
{
echo "username or Password is wrong";
}
}
}
?>
<!-- begin snippet: js hide: false console: true babel: false -->

In model
$res = $this->db->get();
return $res->result_array();
then apply
foreach($answer as $a)
{
var_dump( $a );
}
use $a to get values

$data = json_decode(json_encode($answer),true);
print_r($data);
used this your result convert in array format

You are calling the ->result() in you model and then trying to call the result array from the controller.
Either remove the ->result(); from the return $query->result(); in the model or remove the ->result_array() from the controller.
Once you have called the script and used ->get() you can only call one of the results at a time. If you are likely to want to call different result parameters such as ->result() and ->num_rows on the same query result then just return the query to the controller and use ->result() in the controller.
Hope this helps clear things up a little.
MODEL
class user extends CI_Model
{
function __construct()
{
parent::__construct();
}
function usergetdata( $username,$userpass,$role )
{
$this->db->select();
$this->db->from( 'user' );
$this->db->where( 'username',$username );
$this->db->where( 'userpass',$userpass );
$query= $this->db->get();
if( $query->num_rows() == 1 )
{
return $query;
}
else
{
return false;
}
}
}
CONTROLLER
$answer = $this->user->usergetdata( $username,$userpass,'admin' );
$data = $answer->result_array();

Related

Redirect to controller if query in model return empty in Codeigniter 3

what I want to do is redirect user to another controller if query in my model return empty.
I have controller like this, passing url parameter in $id to get specific user
public function get_user($id)
{
$data['user'] = $this->user_model->get_user_detail($id);
$this->load->view('customer_detail',$data);
}
And my model :
public function get_user_detail($id)
{
$query = $this->db->where('user_id', $id)->get('user');
return $query->row();
}
then I passed the result to my view like this:
<?php echo $user->name;?>
It's worked just fine. The url from my controller will be something like mysite/user/get_user/7 and '7' is the id. But if I typed non existent id directly in the url bar like mysite/user/get_user/99 it will throw error "Trying to get property 'name' of non-object" because there are no user with id 99 in the database. How to redirect user to another controller if there is no data found from the query?
Thanks
A simple way to redirect.
$q = $this->db->query()->row();
If($q==""){
redirect('url/page');
}
public function get_user_detail($id)
{
$query = $this->db->where('user_id', $id)->get('user');
$query != "" ? redirect('actual-controller ($query)') : redirect('other-controller');
}
controller($query){ return $query->row(); //your view code for view here }
Thanks to #Vickel for pointing out. I should do the checking on the controller not in the model and don't need redirect. I was do the checking on the model and redirect.
public function get_user($id)
{
$data['user'] = $this->user_model->get_user_detail($id);
if (!empty($data['user'])) {
$this->load->view('customer_detail',$data);
} else {
$this->load->view('404');
}
}

how to get specific value from db and show result in view codeigniter

i have problem to show my query result in my view, i user codeigniter with mvc structure, in model my code its look like this,
<?php
class Model_Kabalitbang extends CI_Model{
public function getPaguAnggaran(){
$query = "SELECT pagu_anggaran_program_modalutama FROM program_modal_utama WHERE id_program_modalutama = '3'
";
return $this->db->query($query);
}
}
and in my controller i call my model like this
<?php
class Kabalitbang extends CI_Controller{
function __construct(){
parent::__construct();
if($this->session->userdata('logged_in') !== TRUE){
redirect('login');
}
$this->load->model('Model_Kabalitbang');
}
function index(){
//Allowing akses to kabalitbang only
if($this->session->userdata('level')==='2'){
// Jumlah PAGU
$pagu = $this->Model_Kabalitbang->getPaguAnggaran();
$paguanggaran = $pagu->num_rows();
$data = array(
'jml_pagu' => $paguanggaran,
);
$this->load->view('kabalitbang/dashboard_view', $data);
}else{
echo "Access Denied";
}
}
}
but when i call in view <?=$jml_pagu ?> this show just 1, but the value form field in my query is 24392
how to make my code run?
Your query is already return a row containing a number, so you just need to display the row, not counting the row again :
$pagu = $this->Model_Kabalitbang->getPaguAnggaran();
$paguanggaran = $pagu->row_array();
$data = array(
'jml_pagu' => $paguanggaran['pagu_anggaran_program_modalutama'],
);
use this...
$this->db->where('id_program_modalutama ',3);
$result['data']=$this->db->get('Table Name')->result();
$this->load->view('kabalitbang/dashboard_view', $result);
now use loop on $data in your view...
Example :-
foreach($data as $allData)
{
print_r($allData);
}

how to do ? get query object with one model and add where or join condition another model or controller using codeigniter

I have to call a user model and get object only and then add the conditions.
How can I do this?
function manager(){
$email = 'xxxx#gmail.com';
$result = $this->user_model->getUserinformationData( );
$result1= $result->where('user.email',$email);
echo '<pre>';print_r($result1);exit;
}
function getUserinformationData(){
$querysucess = $this->db->select('*')->get('user');
return $querysucess;
}
Only get query object from model and add where or join condition another model or controller how can I do that one.
You have to pass variable from controller to model as function parameter:
//controller method
public function manager()
{
$email = 'xxxx#gmail.com';
$result = $this->user_model->getUserinformationData($email);//pass to the model
echo '<pre>', var_dump($result);
exit;
}
//model method
function getUserinformationData($email)//$email is passed from controller
{
$query = $this->db->get_where('user', ['email' => $email]);//second parameter of get_where() method as array of where conditions
return $query;
}
You have that in docs.

How do I display active record in codeigniter with multiple controllers?

I am building my comment module and trying to get the active records to display on view. Seems simple however I have a lot going on and using a separate model and controller then what the view is being generated from.
So I have a profile page ( where I'm trying to get the results to display )
Controller:
public function profile()
{
$this->load->helper('url'); //Include this line
$this->load->helper('date');
$this->load->library('session');
$this->load->library('form_validation');
$session_id = $this->session->userdata('id'); //Ensure that this session is valid
//TRYING TO MAKE A VARIABLE WITHT THE $_GET VALUE
$user_get = $this->uri->segment(3); // Modify this line
// LOAD THE CORRECT USER
$this->load->model('account_model');
$user = $this->account_model->user($user_get); //(suggestion) you want to pass the id here to filter your record
$data['user'] = $user;
$data['session_id'] = $session_id;
if($user_get != $user['id'] || !$user_get)
{
$data['main_content'] = 'account/notfound';
$this->load->view('includes/templates/profile_template', $data);
}
else
{
if($user_get == $session_id) //Modify this line also
{
$data['profile_icon'] = 'edit';
}
else
{
$data['profile_icon'] = 'profile';
}
$sharpie = $this->sharpie($user);
$data['sharpie'] = $sharpie;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/profile_template', $data);
}
}
Now I have a new controller for my comments I'm trying to display:
public function airwave() {
$this->load->helper('date');
$this->load->library('session');
$airwave_get = $this->uri->segment(3);
$this->load->model('community_model');
$airwave = $this->coummunity_model->airwave($airwave_get);
$data['airwave'] = $airwave;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/main_page_template', $data);
}
with this model:
public function airwave($id=null)
{
if(is_null($id)) {
$session = $this->session->userdata('is_logged_in');
$commenter_id = $this->session->userdata('id');
}else{
$commenter_id = intval($id);
}
$query = $this->db->query("SELECT * FROM airwaves_comments WHERE from_id=$commenter_id");
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
//above returns the single row you need to the controller as an array.
//to the $data['user'] variable.
}
}
and trying to display it on this view ( which is generated by the profile function )
<div class="profile_airwave_comment_text">
<?php echo $airwave['comment'];?>
</div>
I just can't seem to get it to pass the array variable I've created properly to that view?
thanks in advance.
The first glaring thing I see wrong is in you model's airwave function:
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
You are assuming that there will only be one result in your query, so if there are more or less than one, your $data array will bever be set.
Also, even then you are only returning the first element in the array. I am not seeing anywhere in your question that you want to return only one.
Finally, in your view, if you now return the full array, and not only one element, you will have to do a foreach statement.
EDIT: please see suggested solution.
In your model, don't worry about the check for the amount of data in the result array. This will come later. Simply do:
return $query->result_array();
Now, keep your controller as is, but adapt your view:
<div class="profile_airwave_comment_text">
<?php
if (isset($airwave) && is_array($airwave) && !empty($airwave))
{
foreach ($airwave as $wave)
{
echo $wave['comment'];
}
}
else
{
echo 'No comments found...';
}
?>
</div>
This should work, and if not, at least let you know that no comments were fond, and thus check your database.
HTH!
If your using HMVC, simply call the module from inside the profile view, ie:
echo Modules::run('comments/profileComments', $user->id);
Else:
You would need to create a new method in the loader class, to load in the controller seperate from routing.
If your really after a quick fix until you come up with a better alternative, you could(depending if both controllers live in the same directory) just include the 'comments' controller in your 'profile' controller and try something like this:
{Cons: CI Pagination wont work!}
application/controllers/profile.php
include 'Comments' . EXT;
class Profile extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function index( $user_id ){
$commentsPartialView = call_user_func_array(array(new Comments(), "getProfileComments"), array($user_id));
return $this->load->view($this->template, array(
'view' => 'profiles/_index',
'comments' => $commentsPartialView
));
}
}
-
application/controllers/Comments.php
class Comments extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function getProfileComments( $user_id ){
$user_comments = ''; //pull from DB
//set third param to TRUE for partial view, without main template
return $this->load->view('comments/show', array(
'user_comments' => $user_comments
), TRUE);
}
}

Codeigniter Active Records Fatal Error

new to stack overflow (and codeigniter!) and I'm running into this issue on my first project, naturally... I'm sure its a bonehead error on my part, but I've been researching and trying to figure it out for the last few hours and I cat seem to figure it out...
I have the database library autoloaded, but everytime I try to use the methods in my model I get this error:
"Fatal error: Call to a member function where() on a non-object in application\models\user_model.php on line 13"
this is my User controller method called by the form action from my login form view:
function login() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query)
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('members');
}
else
{
$this->load->view('user');
}
} // end login function
this is my model:
<?php
class User_model extends CI_Model {
function __construct() {
parent::__construct();
}
// -------------------------------------------------------------------------------
// validate(): query db for user/pass and return true or false
function validate() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', sha1($this->input->post('password')));
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
return true;
}
} // end validate function
// -------------------------------------------------------------------------------
function check()
{
$dbo = $this->load->database('default',TRUE);
$query = $this->$dbo->get('users');
echo $query->num_rows();
}
} // end user_model class
when I was attempting to debug the issue, I added the db methods to the controller and they worked fine... when using them in my model they dont want to work for whatever reason and throw the fatal error I mentioned. Appreciate any help you guys can throw my way.
Thanks in advance!
(using codeigniter 2.1)
EDIT:
Just to clear things up a little bit more, When I add the validate method (from my model) to my controller, I get no errors, and everything works fine... But when leaving it in the model and calling it from the controller I get the fatal error
You missed $query = part, Should be:
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
return true;
}
Edited:
I think you have not added all the parent constructor, try:
class Users extends CI_Model {
function __Users() {
parent::__CI_Model();
$this->load->database();
}
I think the function validate in your model should be like this
// validate(): query db for user/pass and return true or false
function validate($username,$password) {
$this->db->where('username', $username);
$this->db->where('password', sha1($password));
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
return true;
}
} // end validate function
In your controller you can call it like so
function login()
{
$query =$this->user_model->validate($this->input->post('username'),$this->input->post('password'));
// the rest
}

Categories