I want to have a simple helper which records one hit in my database. I have created a $CI instance and attempt to access the model like this...
$CI->load->model('stats_model');
$CI->stats_model->set_hit();
But i get an error in the model..
Severity: Notice
Message: Undefined property: Stats_model::$db
Filename: models/stats_model.php
Line Number: 16
Line 16 is a simple...
$this->db->select('*');
I got the idea to do this from this link http://blog.avinash.com.np/2010/07/01/talk-to-the-database-from-a-helper-codeigniter/
I have tried $CI->db... instead of $this->db in the model but still no luck, any ideas?
HELPER
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
function check_hit() {
//stuff that uses CI
$CI = & get_instance();
$CI->load->library('user_agent');
if ($CI->agent->is_robot()) {
return FALSE;
} else {
//check for a 12 hour cookie
$check = $CI->input->cookie('stat');
if ($check == false) {
//insert a database entry
$CI->load->model('Stats_model');
$CI->Stats_model->set_hit();
//set a cookie
$cookie = array(
'name' => 'stat',
'value' => '1',
'expire' => '43200'
);
// $CI->input->set_cookie($cookie);
}
}
}
check_hit();
?>
MODEL
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Stats_model extends Model {
function Stats_model() {
// Call the Model constructor
parent::Model();
}
function set_hit() {
$date = date('Y-m-d');
$this->db->select('unique_visitors');
$this->db->from('daily_stats');
$this->db->where('date', $date);
$query = $this->db->get();
$date_rows = $query->num_rows();
$result = $query->row();
$visits = $result->unique_visitors;
$visits++;
$data = array(
'unique_visitors' => $visits,
'date' => $date
);
if ($date_rows == 1) {
$this->db->where('date', $date);
$this->db->update('daily_stats', $data);
} else {
$this->db->insert('daily_stats', $data);
}
}
}
?>
This part was a little confusing for me a while back. This seemed to work.
//load the CI instance
$this->ci =& get_instance();
//run a db get
$this->ci->db->get('mytable');
Related
Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$this->form_validation-> set_rules('username', 'Username', 'required');
$this->form_validation-> set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}
http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();
I have tried many ways of getting the username in codeigniter models. that matches the row id. But can not seem to get my model to work.
I have looked at user guide many times all ways get errors.
It shows the row id / user id OK when echo it
But can not seem to make a model to be able to match username with row id and then echo it.
Any suggestion on suitable model function.
when I click on my edit button it shows up in url http://localhost/codeigniter/codeigniter-blog/admin/users/edit/1 which works.
Model
// Not return username that matches id.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_user extends CI_Model {
function getUsername() {
$this->db->select('username');
$this->db->where('user_id');
$query = $this->db->get('user');
return $query->row();
}
}
Controller function.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('user');
if ($this->session->userdata('isLogged') == TRUE) {
return true;
} else {
redirect('/');
}
}
public function index() {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['text_enabled'] = "Enabled";
$data['text_disabled'] = "Disabled";
$results = $this->model_user->getUsers();
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'edit' => site_url('users/edit/' . $result['user_id'])
);
}
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_list', $data);
}
function edit($user_id = 0, $user_group_id = 0) {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['user_id'] = "Current User ID" . " " . $user_id . ":";
$data['user_group_id'] = "Current User Group ID" . " " . $user_group_id . ":";
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername();
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
}
}
'where' requires a second argument, which you would pass as an argument to your model function. so something like this in the model
class Model_user extends CI_Model {
function getUsername($id) {
$this->db->select('username');
$this->db->where('user_id', $id);
$query = $this->db->get('user');
return $query->row();
}
}
this corresponds to an sql query like
SELECT username FROM user WHERE user_id = ?
so in the controller just pass the user id in the argument to the model function
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername($user_id);
I have found best way to get my username to match user id
On My Model
function getUsername($user_id) {
if (empty($user_id)) {
return FALSE;
}
$this->db->select('username');
$this->db->where('user_id', $user_id);
$query = $this->db->get('user');
if ($query->num_rows() == 1) {
$result = $query->result_array();
return $result[0]['username'];
} else {
return FALSE;
}
}
on Controller function
$this->model_user->getUsername($user_id);
Hi i have this form when save, saved into the database. I want that when the data is saved into the database i will get the id on it then displaying it to the next page.
Here's my controller below in my function add_new
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Create_album extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->model('admin_model', 'am');
$this->load->library('form_validation');
if(!$this->session->userdata('logged_in')){
redirect('login');
}
}
public function detail($id){
return $id;
$this->data['item'] = $this->am->getItem($id);
print_r($this->data['item']);exit;
}
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$itemId);
}
}
public function index(){
$this->data['title'] = 'Create Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}
}
my model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Admin_model extends CI_Model{
public function getItem($id){
return $this->db->select('item.id,
item.parent_id,
item.title,
item.description,
item.filename
'
)
->from('item')
->where('item.id', $id)
->get()->result_object();
$this->db->get('item');
}
}
?>
Can someone help me figured this out? i want to get the ID when the data is saved. Any help is muchly appreciated. Thank you
Simply use this
$this->db->insert_id(); // Returns your row id.
Here how your controller should look like
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id()); // here?
}
}
Think you're probably looking for the insert_id() query helper function. You can see info about it in the Codeigniter docs.
When PHP hits return in a function it does just that, return a value, and it exits the function. Code following the return will not be executed. Read about it on the docs page
Example:
public function detail($id){
return $id;
echo 'here';
}
You will never get 'here' to echo, since you have already returned a value in your function().
Again this applies twice in your code, once here:
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id());
and again here:
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
If you want the insert id you are going to have to return it from $this->am->saveAlbum(); Assign that to a variable and pass it to your redirect.
There are quite a few other issues, but that should help to get you started.
i'm new with CI and i tried a lot posibilities to make this run, but still it ain't working. Could you please tell me what i'm doing wrong?
So, Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('model_add','',TRUE);
}
public function _remap($a){
if (isset($a) && !empty($a)):
switch ($a) {
case 'index':
$this->index();
break;
default:
$this->one_news($a);
break;
}
endif;
}
public function index()
{
$this->load->library('pagination');
$home=$this->uri->segment(2);
$limit=2;
$offset=0;
$query=$this->model_add->count_news($limit,$offset);
$config['base_url'] = base_url().'/news/';
$config['total_rows'] = $this->db->count_all('tdt_news');
$config['per_page'] = 2;
$config['uri_segment'] = 2;
$this->pagination->initialize($config);
$data = array('query' => $query,'page'=>$home);
$data['news'] = $query;
$this->load->view('main/header');
$this->load->view('main/news', $data);
$this->load->view('main/footer');
}
}
And the Model:
function count_news()
{
$query=$this->db->query("SELECT * FROM `tdt_news` ORDER BY `id` DESC LIMIT $limit, $offset;");
return $query->result();
}
I'll be very thankful for your help, thank you!
You have a series of errors
your count function in your model is missing parameters
you should reformat the SQL string
alternate and standard syntax in your view
renamed model class to empty string
heres a fixed version,
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('model_add');
}
public function _remap($a){
if (isset($a) && !empty($a)) {
switch ($a) {
case 'index':
$this->index();
break;
default:
$this->one_news($a);
break;
}
}
}
public function index()
{
$this->load->library('pagination');
$home = $this->uri->segment(2);
$limit = 2;
$offset = 0;
$query=$this->model_add->count_news($limit,$offset);
$config['base_url'] = base_url().'/news/';
$config['total_rows'] = $this->db->count_all('tdt_news');
$config['per_page'] = 2;
$config['uri_segment'] = 2;
$this->pagination->initialize($config);
$data = array( 'query' => $query,
'page'=>$home,
'news' => $query);
$this->load->view('main/header');
$this->load->view('main/news', $data);
$this->load->view('main/footer');
}
}
Model:
// with default parameters just in case
function count_news($limit = 50, $offset = 0)
{
// and there is a nicer way to write your query
// it works with multiple dbs thanks to active record
$this->db->order_by('id','desc');
$query = $this->db->get('tdt_news', $limit, $offset);
return $query->result();
}