Function won't pass variable to view - php

Right now $renderData['username'] won't pass through to the view.
class HomeController extends MY_Controller {
public function index($renderData=""){
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$renderData['username'] = $session_data['username'];
//$this->load->view('pages/home_view', $renderData);
$this->_render('pages/home',$renderData);
}
else
{
//If no session, redirect to login page
redirect('LoginController', 'refresh');
}
}
}
The error I get is...
Which alludes to this code...
<h1>Home</h1>
<h2>Welcome <?php echo $username; ?>!</h2>
Logout
Here is my My_Controller where the _render function is located...
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller{
//Page info
protected $data = Array();
protected $pageName = FALSE;
protected $template = "main";
protected $hasNav = TRUE;
//Page contents
protected $javascript = array();
protected $css = array();
protected $fonts = array();
//Page Meta
protected $title = FALSE;
protected $description = FALSE;
protected $keywords = FALSE;
protected $author = FALSE;
function __construct()
{
parent::__construct();
$this->data["uri_segment_1"] = $this->uri->segment(1);
$this->data["uri_segment_2"] = $this->uri->segment(2);
$this->title = $this->config->item('site_title');
$this->description = $this->config->item('site_description');
$this->keywords = $this->config->item('site_keywords');
$this->author = $this->config->item('site_author');
$this->pageName = strToLower(get_class($this));
}
protected function _render($view,$renderData="FULLPAGE") {
switch ($renderData) {
case "AJAX" :
$this->load->view($view,$this->data);
break;
case "JSON" :
echo json_encode($this->data);
break;
case "FULLPAGE" :
default :
//static
$toTpl["javascript"] = $this->javascript;
$toTpl["css"] = $this->css;
$toTpl["fonts"] = $this->fonts;
//meta
$toTpl["title"] = $this->title;
$toTpl["description"] = $this->description;
$toTpl["keywords"] = $this->keywords;
$toTpl["author"] = $this->author;
//data
$toBody["content_body"] = $this->load->view($view,array_merge($this->data,$toTpl),true);
//nav menu
if($this->hasNav){
$this->load->helper("nav");
$toMenu["pageName"] = $this->pageName;
$toHeader["nav"] = $this->load->view("template/nav",$toMenu,true);
}
$toHeader["basejs"] = $this->load->view("template/basejs",$this->data,true);
$toBody["header"] = $this->load->view("template/header",$toHeader,true);
$toBody["footer"] = $this->load->view("template/footer",'',true);
$toTpl["body"] = $this->load->view("template/".$this->template,$toBody,true);
//render view
$this->load->view("template/skeleton",$toTpl);
break;
}
}
}
Here is an additional function that may be helpful...
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('pages/login_view');
}
else
{
//Go to private area
// redirect('home', 'refresh');
redirect('HomeController', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
What am I doing wrong that is preventing the username to be passed to the view?
PS - let me know any additional documentation I can provide.

something like this
protected function _render($view,data, $renderData="FULLPAGE") {
$this->data = $data;
switch ($renderData) {
case "AJAX" :
$this->load->view($view,$this->data);
break;
case "JSON"

Related

I Have Some Problems in codeigniter with sessions

I try to check when someone logged in his/her account show the page with the session, I loaded session in libraries but the session doesn't work
And Sorry For My Bad English
Thanks For The Help :)
This Is The Model
class login_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function check()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$remember = $this->input->post('remember');
$this->db->select('username','password');
$this->db->from('user');
$this->db->where('username',$username);
$this->db->where('password',md5($password));
$result = $this->db->count_all_results();
if($result > 0)
{
$data_session = array(
'username'=>$username,
'islogin'=>true,
);
$this->session->set_userdata($data_session);
redirect('post/index');
}
This Is The Controller
class Post extends CI_Controller
{
public function index()
{
$login = $this->session->userdata('islogin');
if($login == true)
{
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
else {
redirect('login/index');
}
}
}
This Is The Config
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'weblogdata';
$config['sess_expiration'] = 3600;
$config['sess_save_path'] = 'tbl_ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
$config['encryption_key'] = m.D~wt,wA:MjS9$]g<H4Z7eW.7`0vDbX$F`LUgCg+>$1?0L$vq1:7vaVf&d{U(
set your session condition on contruct(), change the controller to be like this :
function __construct() {
parent::__construct();
if($this->session->userdata('islogin') != true)
{
redirect('login/index');
}
}
function index() {
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
change your code to this
class Post extends CI_Controller
{
public function index()
{
$login = $this->session->userdata('islogin'); // $login will be 1
if($login)
{
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
else {
redirect('login/index');
}
}
}

How to dynamically display user name from the database after log in?

I need to dynamically display user name from logged in user in my OOP PHP project. I can display it when I type right id from the database but it shows error when I try to define property $user_id in my function find_by_id. I need help on how to define $user_id variable. Here is my code:
index.php
<?php $user = User::find_by_id($user_id); ?>
<h1>Hello, <?php echo $user->username; ?></h1>
user.php
<?php
class User
{
protected static $db_table = "users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all()
{
return self::find_this_query("SELECT * FROM " . static::$db_table . " ");
}
public static function find_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM " . self::$db_table . " WHERE id = $user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM " . self::$db_table . " WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
For the sake of marking this as accepted, what you need to do is actually pass the user ID of the and not just an uninitialised variable, if your instance you are storing it in the session so I presume it would be:
<?php $user = User::find_by_id($_SESSION['user_id']); ?>
Note: To make your templating cleaner, you can use the shorthand syntax for echo:
<h1>Hello, <?= $user->username; ?></h1>
Another thing to note is that you have built a Session class, however you are still for some reason accessing the data through $_SESSION which doesn't make sense, make some setters / getters for it. Finally, sessions are something that you'll be using a lot therefore it would be worth making that class static.
Reading Material
echo

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.

Pass variable from one function to another

HOw do I pass $variable from comments() to someFunction()?
class Blog extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
public function comments()
{
$variable = "Hello";
}
public function someFunction()
{
echo $variable;
}
}
** EDIT ** Feel free to point out any other mistakes if you wish
class Home extends CI_Controller {
private $idArray;
function __construct()
{
parent::__construct();
$this->load->model('home_model');
$this->load->library('tank_auth');
$this->load->library('form_validation');
}
public function index() {
$home_data['initial_two'] = $this->home_model->get_two_brands();
$home_data['user_id'] = $this->tank_auth->get_user_id();
$home_data['username'] = $this->tank_auth->get_username();
$this->load->view('home_view', $home_data);
}
public function get_two() {
$get_results = $this->home_model->get_two_brands();
if($get_results != false){
$html = '';
foreach($get_results as $result){
$html .= '<li>'.$result->brand.'</li>';
}
list($result1, $result2) = $get_results;
$idOne = $result1->id;
$idTwo = $result2->id;
$this->idArray = array($result1->id, $result2->id);
//var_dump($this->idArray);
$result = array('status' => 'ok', 'content' => $html);
header('Content-type: application/json');
echo json_encode($result);
exit();
}
}//public function get_two() {
function user_pick() {
$this->form_validation->set_rules('pick', 'Pick', 'required|trim|integer|xss_clean');
$this->form_validation->set_rules('notPick', 'Not Pick', 'required|trim|integer|xss_clean');
//$arr = $this->idArray;
var_dump($this->idArray); // This is NULL
$pick = $_POST['pick'];
$notPick = $_POST['notPick'];
$user_id = $this->tank_auth->get_user_id();
if ($this->form_validation->run() == FALSE)
{
$result = array('status' => 'no', 'content' => "No good!");
header('Content-type: application/json');
echo json_encode($result);
exit();
}else{//if ($this->form_validation->run() == FALSE || $do_input == NULL)
$upload = $this->home_model->user_pick($user_id, $pick, $notPick);
$result = array('status' => 'ok', 'content' => "Thank you!");
header('Content-type: application/json');
echo json_encode($result);
exit();
}//if ($this->form_validation->run() == FALSE || $do_input == NULL)
}
}//class Home extends CI_Controller { closing bracket
/* End of file home.php */
/* Location: ./application/controllers/home.php */
class Blog extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
public function comments()
{
$_SESSION['variable'] = Array('k1'=>'v1','k2'=>'v2') ;
// Store the variable in session so it can be called
// in another page or ajax call
}
public function display()
{
echo $_SESSION['variable'] ;
}
}
// my index.php file
var $blog = new Blog() ;
$blog->comments() ;
//another ajax_called.php file, call in ajax on in another browser tab
var $blog = new Blog() ;
$blog->display() ;

500 error while loading the Model on Controller Class

I am working with Codeigniter 2.1.4 and also new to this framework. When ever i am trying to load the model on the controller class, error id 500 being thrown by the browser. Here is the code of the model class file name:
merchant_login.php
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Merchant_model extends MY_Model {
public $tbl_user = 'users';
function __construct(){
parent::__construct();
$this->load->database('merchant', TRUE, TRUE);
}
function user_login($data)
{
$this->db->from($this->tbl_user);
$this->db->where($data);
$query = $this->db->get();
if($query->num_rows()==1)
{
$this->db->select("CURRENT_LOGIN");
$this->db->from($this->tbl_user);
$this->db->where("USER_ID", $data["USER_ID"]);
$q = $this->db->get();
$res = $q->result();
$current_time = $res[0]->CURRENT_LOGIN;
$last_time = $current_time;
$current_time = date("Y-m-j H:i:s");
$arr = array(
"CURRENT_LOGIN" => $current_time,
"LAST_LOGIN" => $last_time,
"LAST_IP" => $this->input->ip_address()
);
$this->db->where("USER_ID", $data["USER_ID"]);
$this->db->update($this->tbl_user, $arr);
$this->db->from($this->tbl_user);
$this->db->where($data);
$query = $this->db->get();
return $query->row_array();
}
return false;
}
} ?>
Here is the code for controller and the file name is:
"login.php"
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->library(array("form_validation", "session"));
}
//merchant section start
public function merchant_login() {
$this->session->keep_flashdata("return_url");
$this->form_validation->set_rules('loginName', 'Login', 'trim|valid_email|required');
$this->form_validation->set_rules('loginPassword', 'Password', 'trim|required');
if ($this->session->userdata("merchantLogged") != 1) {
if ($this->form_validation->run() == FALSE) {
$data["error"] = validation_errors();
header('Content-type: application/json');
echo json_encode($data);
} else {
$d['USER_ID'] = $this->input->post("loginName");
$d['USER_PASSWD'] = sha1($this->input->post("loginPassword"));
$this->load->model("merchant_model", "model", TRUE);
$user = $this->model->user_login($d);
if ($user) {
if ($this->input->post("security") == 'not') {
//Cal to a member function of the model class
if ($this->model->user_ip_check($d) == false) {
$this->session->set_userdata('u_id', $this->input->post("loginName"));
$this->session->set_userdata('u_pd', $this->input->post("loginPassword"));
$data['redirect'] = site_url("merchants/ip_security/");
} else {
$usr['type'] = "MR";
unset($user['USER_PASSWD']);
// unset($user['ID']);
unset($user['MM_NAME']);
//$this->load->database('default', TRUE, TRUE);
$this->session->set_userdata($usr);
$this->session->set_userdata($user);
$this->set_merchantLogged(1);
// if($this->session->flashdata("return_url")){
// $data['redirect'] = site_url("user/" . $this->session->flashdata("return_url"));
// }
// else{
$data['redirect'] = site_url("merchant/account");
// }
}
} else {
$d['que'] = $this->input->post("sec_q");
$d['ans'] = $this->input->post("sec_q_answer");
if ($this->model->check_que($d) == true) {
$this->session->unset_userdata('u_id');
$this->session->unset_userdata('u_pd');
$usr['type'] = "MR";
unset($user['USER_PASSWD']);
unset($user['MM_NAME']);
$this->session->set_userdata($usr);
$this->session->set_userdata($user);
$this->set_merchantLogged(1);
$data['redirect'] = site_url("merchant/account");
} else {
$data['redirect'] = site_url("merchants/ip_security");
}
}
} else {
$data["error"] = "Username or password are wrong";
$data["islogin"] = true;
}
header('Content-type: application/json');
echo json_encode($data);
}
} else {
if ($this->session->flashdata("return_url")) {
$data['redirect'] = site_url("merchant/" . $this->session->flashdata("return_url"));
} else {
$data['redirect'] = site_url("home");
}
header('Content-type: application/json');
echo json_encode($data);
}
}
}
?>
class Merchant_model extends MY_Model
replace
class Merchant_model extends CI_Model
class Login extends MY_Controller
replace
class Login extends CI_Controller
syntax error:$this->load->database('merchant', TRUE, TRUE); correct this one
My Suggestion please go through on the codeigniter document it can helpfull you
http://ellislab.com/codeigniter/user-guide/general/controllers.html
change your model file name from merchant_login.php to merchant_model.php
and change in login.php
$this->load->model("merchant_model", "model", TRUE);
to
$this->load->model("merchant_model", "", TRUE);

Categories