Not loading view by calling method - php

I made a user table that will link to his postings when he submits a post. (It parts works correctly)
So I have been trying to create a method in codeigniter 3. I have it set to where if the user is logged in and clicks his user name it will show all his submissions, by simply pulling from the table his user_id and then looping through his posts.
Well, I have two issues
when I enter in the url to call this function it wants a value for the uri. Example: localhost/CI/controller/account yet it will not load until I put something after account (account is the method name).
Like localhost/CI/controller/account/9
Also this function does not seem to work either for some reason, I do not know if it has something to do with it wanting another value.
I have researched this for the past hour with no luck.
Controller:
public function account(){
$data['title'] = 'Your submissions';
$data['posts'] = $this->post_model->user_posts();
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}
//view function the post by clicking on title
public function view ($slug=NULL){
$data['post'] = $this->post_model->get_posts($slug);
$post_id = $data['post']['id'];
$data['comments'] = $this->comment_model->get_comments($slug);
if(empty($data['post'])){
show_404();
}
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
}
Model:
public function user_posts (){
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts',array('customer_id ='=>'$usernum'));
return $query->result_array();
}
$query = $this->db->get_where('posts',array('slug'=>$slug));
return $query->row_array();
}
View:
<?php
echo $title;
foreach ($posts as $post): {
echo $post['title'];
}endforeach;
?>

Controller :
public function account($acno = "") {//changes
$data['title'] = 'Your submissions';
$data['posts'] = $this->Post_model->user_posts();//changes
echo'<pre>';print_r($data);die;//changes
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}
Model :
public function user_posts() {
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time', 'DESC');
$query = $this->db->get_where('posts', array('customer_id =' => $usernum));//changes
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return array();
}
}

Change model function like this
public function user_posts (){
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts', array('customer_id' => $usernum));
return $query->result_array();
}
The associative array does not need = in where() or get_where() to get the record
Do not need single quotes with $usernum

After trying somethings this is what corrected my issues
Public function user_posts (){
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts', array('customer_id' => $this->session->userdata('customer_id')));
return $query->result_array();
}
I believe by removing the $usernum = $this->session->userdata('customer_id'); and adding it to the query, now allows the user to call his own session id without the need to enter one into the function.
Thanks to those that gave me input

I dont know how your button click is set up but this is how you should do it.
Button click page
<?= site_url(); ?>controller_name/account
account function in controller
function account(){
//1. Check if user is Logged in
if (!$this->ion_auth->logged_in())
{
//If they are not logged in, redirect them to login page or do something
}
else{
//User is logged in so get submissions
//Get all submissions
$data['title'] = 'Your submissions';
$this->data['posts']= $this->post_model->user_posts();
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}}
User posts function in Model
function user_posts (){
$user = $this->ion_auth->user()->row();
$ref_id=$user->id; //Gets you user id
$this->db->where(['customer_id'=>$ref_id]);
$this->db->order_by('created_time','DESC');
$query=$this->db->get('posts');
if($query->result())
{
return $query->result();
}
else
{
return false;
}}
Also, consider using Ion Auth for your login in codeigniter as it allows you access session data easily without issues as the one you've been facing.

Related

Set session values with query result in CodeIgniter 3

I have a function in my model that checks the credentials given in the login form. It selects the email, senha and tipo_pessoa. Below is the function:
public function find_credentials()
{
$this->db
->select('email, senha, tipo_pessoa')
->from($this->table)
->where('email', $this->input->post('email'))
->where('senha', md5($this->input->post('password')));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
}
return false;
}
The next function, located in my Controller, is executed regardless of the results of the previous function. It decides what to do depending on the returned result:
public function validate_credentials()
{
if ($this->Usuarios_fisica_model->find_credentials()) {
$data = array();
$data['email'] = $this->input->post('email');
$this->session->set_userdata($data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
}
I need to store tipo_pessoa in the session to determine which page the user should be redirected to. I have two different tables for two different kind of users, and each kind has its own page.
Edit*
After the suggested solutions, I added to my header file the following code to echo the tipo_pessoa:
<div class="menu_login">
<?php if ($this->session->userdata('email')) { ?>
<span><?php echo $this->session->userdata('email'); ?></span>
<span><?php echo $this->session->userdata('tipo_pessoa'); ?></span>
Ir ao Painel
Sair
<?php } else { ?>
<span>Minha Conta</span>
Entre
Cadastre-se
<?php } ?>
</div>
Use this changes in Model:
$query = $this->db->get();
return $query->result();
and make this changes to controller:
$data = $this->Usuarios_fisica_model->find_credentials();
if(!empty($data))
{
$tipo_pessoa = $data[0]['tipo_pessoa']; //Get value of tipo_pessoa
$this->session->set_userdata('tipo_pessoa', $tipo_pessoa);//Set value in session
//your if part code
}
else
{
//your else part code
}
Here's an example of how to set session data from the results of a query:
function get_something()
{
$this->db->select('something');
$something = $this->db->get('table')->row();
$this->session->set_userdata('something',$something);
}
With your example model:
$this->db
->select('email, senha, tipo_pessoa')
->from($this->table)
->where('email', $this->input->post('email'))
->where('senha', md5($this->input->post('password')));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result_array();
}
return false;
controller:
if ($something = $this->Usuarios_fisica_model->find_credentials()) {
$data = array();
$data['email'] = $this->input->post('email');
$this->session->set_userdata('tipo_pessoa', $something['tipo_pessoa']);
$this->session->set_userdata($data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
Instead of doing what I intended to do, I simply put a select box in the login page to choose between the two different types. Now it is easy to retrieve the value and make the choices.

Codeigniter How to redirect back to previous page without losing data

here is my items controller, it displays list of items, and view it from items_view.php.
class Items extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('crud');
}
function index(){
$data['items'] = $this->crud->read('items');
$data['header_info'] = $this->crud->header_info('items');
#$data['single_row'] = $this->crud->read_single('items','ID', 1);
$this->load->view('items_view', $data);
}
function edit($id){
$data['single_row'] = $this->crud->read_single('items','ID', $id);
$this->load->view('items_view', $data);
}
function insert(){
if($_POST){
$data = array(
'Desc' => $_POST['Desc'],
'Cost' => $_POST['Cost']
);
if($_POST['status']=='update'){
$this->crud->update('items', $data, 'ID',$_POST['id']);
echo "Updated...";
}elseif ($_POST['status']=='new'){
$last_row = $this->crud->insert('items', $data);
if($last_row){
#Data insertion completed.....
#now ready to get back my items list page.....!
}
}
}
}
}
in the items_view.php also have form that can user add some more items to the list, so that i would like, when user submit the form the insert method will execute, so how to get back to my previous page without losing data.
In insert() take the id if inserted row or updated row Then redirect to index() like this
redirect("items/index/".$last_row);
In index()
function index($id = ""){
if($id) {
// fetch data from db and pass it to view
} else {
// pass empty value to view
}
$data['items'] = $this->crud->read('items');
$data['header_info'] = $this->crud->header_info('items');
$this->load->view('items_view', $data);
}

How to Update Data in CodeIgniter?

First, sorry for my bad english, if you don't understand what I'm saying, you can ask for it and I will search for another suitable and precise words.
Now, I've been working with codeigniter in this last 2 weeks, so I got so many question for it, but I found 1 which is hanging on my mind.
I started with simple CRUD, then make it advanced, it's good so far, until I got stuck while updating data. When I click the "submit" button, I get only 404 page. And when I see the database, nothing change.
Here's the controller's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Master_user extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('mod_master_user');
$this->load->library('datatables');
}
public function index(){
if ($this->session->userdata('type') == 'admin') {
$data['hasil'] = $this->mod_master_user->getall();
$datum['content'] = $this->load>view('master_user/view',$data,true);
$this->load->view('main',$datum);
} else if ($this->session->userdata('type') == 'user'){
$a= $this->load->model('m_absensi');
$aa["content"] = $this->load->view('absensi/form',$a,true);
$this->load->view("absensi/mainUser",$aa);
}
}
public function tambah_data(){
if($this->input->post('nama')){
$this->mod_master_user->tambah();
redirect('master_user');
}else{
$this->load->view('master_user/add');
}
}
public function update_data($id_user)**//i use this method for updating data**{
if($this->input->post('submit')){
$this->mod_master_user->update($id_user);
redirect('master_user/index');
}
$data['hasil']=$this->mod_master_user->getById($id_user);
$this->load->view('master_user/edit',$data);
}
public function delete_data($id_user){
$this->mod_master_user->delete($id_user);
redirect('master_user');
}
public function error()
{
$this->output->set_status_header('404');
$data['content'] = '404';
$this->load->view('master_user/404',$data);
}
public function print_report()
{
$this->load->view('master_user/print');
}
public function jam_masuk()
{
$this->load->view('master_user/jam_masuk');
}
}
Here comes the model's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Mod_master_user extends CI_Model{
var $tabel_name = 'master_user';
function __construct() {
parent::__construct();
}
public function getall(){
$ambil_data = $this->db->get('master_user');//mengambil tabel master_user
if ($ambil_data->num_rows() > 0 ){ //jika data lebih dari 0
foreach ($ambil_data->result() as $data){
$hasil[] = $data;
}
return $hasil;
}
}
public function tambah(){
$id_user = $this->input->post('id_user');
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$tanggal_lahir = $this->input->post('tanggal_lahir');
$tempat_lahir = $this->input->post('tempat_lahir');
$role = $this->input->post('role');
$data = array (
'id_user'=> $id_user,
'nama'=>$nama,
'password'=>md5($password),
'tanggal_lahir'=>date('Y-m-d',strtotime($tanggal_lahir)),
'tempat_lahir'=>$tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->insert('master_user', $data);
}
public function update($id_user)**//i use this method to updating data**{
$id_user=$this->input->post('id_user');
$nama=$this->input->post('nama');
$password=$this->input->post('password');
$tanggal_lahir=$this->input->post('tanggal_lahir');
$tempat_lahir=$this->input->post('tempat_lahir');
$role=$this->input->post('role');
$data = array (
'id_user' => $id_user,
'nama' => $nama,
'password'=> $password,
'tanggal_lahir'=> $tanggal_lahir,
'tempat_lahir'=> $tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->update('master_user',$data); //update data
}
public function getById($id_user){ //mengambil data dari db berdasarkan id (primary key)
return $this->db->get_where('master_user',array('id_user'=>$id_user))->row();
}
public function delete($id_user){
$this->db->where('id_user',$id_user);
$this->db->delete('master_user'); //query delete data
}
public function cek_user_login($username, $password) {
$this->db->select('*');
$this->db->where('NAMA', $username);
$this->db->where('PASSWORD', md5($password));
$query = $this->db->get($this->tabel_name, 1);
if ($query->num_rows() == 1) {
$this->db->limit(1);
return $query->row_array();
}
}
public function validasi()
{
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$check = $this->mod_master_user->check($nama, md5($password));
if($check->num_rows() > 0)
{
//login berhasil, buat session
//$this->session->set_userdata('username',$username);
redirect('master_user');
}
else
{
//login gagal
//$this->session->set_flashdata('message','Username atau password salah');
redirect('users');
}
}
}
So far, I get no answer on other forums, so I asked for the answer here :)
Any answer/help will be appreciated. Thank you :)
It's been some time since I used CodeIgniter.
Are you loading the input class? so you can actually receive $_GET and $_POST data? I think it does this by default actually.
This might be a bit too simple, but are you calling the right URI and are you sure its reaching your view??
Might help to see your view, are you using the form helper for this? https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
If you get 404, then the problem is in your form action tag. It means it doesn't post to the right url.
This is most likely (if not surely) due to a bad route.
In config/routes.php, you need a route like: $route['master_user/update/(:any)'] = 'master_user/update_data/$1;
And in your view you would need a form with the action pointing to that route, such as:
<form action="master_user/update_data/1">
<!-- your fields and submit button -->
</form>
Where the number 1 (in the action url) is the id of the register being updated.

how to insert a value to a foreign key using session without overriding the other sessions in codeigniter?

I hope you're doing fine. Can somebody help me with my problem? I have 2 tables. The other one is for customers, it has an auto-increment value for customer_id. The other table is for orders, it has an auto-increment also for its orders_id and a foreign key from the other table (customers).
When I insert a new customer, if it is successful, I want the page to be redirected to the add new order page. In inserting new order, the customer_id field in my orders table should have the same value as the newly added customer. Adding customer and adding new order is of different function in my controller. I am having an error 1452 when inserting the new order, which means the value inserted for the foreign key customers_id in the orders table is different with the value in the other table (customers).
Now, I've got this solution using session. My problem is the other session for getting the last id is overriding the session for logging in.
Here's some code snippets from my controller:
Class MyController extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->c_id = 0;
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
if($session_data['username'] == 'administrator'){
$this->load->database('sample');
$this->load->model('samplemodel_model');
$this->load->library('form_validation');
} else {
redirect('home', 'refresh');
}
} else {
redirect('login', 'refresh');
}
}
public function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
//code for validation here
$customers = $this->samplemodel_model->get_entries('customers');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert $data
//$data = array('xxxxxx');
//data is something like that
$this->create($data);
}
}
else
{
//If there's no session it will redirect to login page
}
}
//add new orders
public function addOrders() {
if($this->session->userdata('last_inserted_id')) //if I use this session, I can get the last inserted ID but the session data for the login will not be retrieved.
{
$session_data = $this->session->userdata('last_inserted_id');
$orders = $this->samplemodel_model->get_entries('orders');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert data
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->createItem($data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
//create customer
public function create($data) {
//Insert data
$customers = $this->samplemodel_model->get_entries('customers');
//$data = array(xxxxx);
//somethin' like that for data array
$this->load->samplemodel_model->create('customers', $data);
//***********************************************************//
// get and save last id inserted //
//***********************************************************//
//query the database
$result = $this->samplemodel_model->get_last_inserted($this->db->insert_id());
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array('customer_id' => $row->customer_id);
$this->session->set_userdata('last_inserted_id', $sess_array);
}
return TRUE;
}
else
{
echo "<script type='text/javascript'>alert('error');</script>";
return false;
}
session_start('last_inserted_id');
//********************************************************//
// end //
//********************************************************//
redirect('myController/addOrders', 'refresh');
}
public function createItem($data) {
//Insert data
$orders = $this->samplemodel_model->get_entries('orders');
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->load->samplemodel_model->create('orders', $data);
//I'm not so sure if it is in this function that I should place the unset for the session 'last_inserted_id'
redirect('home', 'refresh');
}
}
And in my model, I inserted another function which helps me saving the last id inserted. Here's it:
public function get_last_inserted($id)
{
$this -> db -> select('customer_id');
$this -> db -> from('customers');
$this -> db -> where('customer_id', $id);
$this -> db -> limit(1);
$query = $this -> db -> get();
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
PLEEEASE! HELP :'( I would really appreciate if you have any other ideas. THANK YOU SOOOOO MUCH!
The issue is that you're redirecting, Each HTTP request is it's own process with it's own variables, and each request can't access the variables set in other requests.
Try passing the customer ID as a parameter to addOrders(), you can then use the codeigniter way of passing params around :
http://www.example.com/controller/method/paramter
Check the docs :
https://ellislab.com/codeigniter/user-guide/general/controllers.html
under the segment : Passing URI Segments to your Functions
Other possible solution : Store the customerID in the session, or in a user object you instantiate when you create a new user, but that's more dependent of the use case.

Codeigniter user functionality

im working on a project at the moment that allows users to register and log into there own user area and add/edit/delete note snippets.
Im currently working on the edit class and im wondering how can i make it so that other users cant visit the same url and edit someones note? (all notes are stored in the same table in the database)
schema = id, title, description, snippet, user_id
for example if user1 wants to edit his note at http://domain.com/edit/1 (which is bound to his user_id in the database) how can i stop user2 from visiting that same url and editing his note?
here is the controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Mysnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['private_snippets'] = $this->dashboard_model->private_snippets();
$this->load->view('dashboard/my_snippets', $this->data);
}
function edit_snippet($snippet_id) {
$snippet = $this->dashboard_model->get_snippet($snippet_id);
//validate form input
$this->form_validation->set_rules('title', 'Title', 'required');
if (isset($_POST) && !empty($_POST))
{
$data = array(
'title' => $this->input->post('title'),
);
if ($this->form_validation->run() === true)
{
$this->dashboard_model->update_snippet($snippet_id, $data);
$this->session->set_flashdata('message', "<p>Product updated successfully.</p>");
redirect(base_url().'mysnippets/edit_snippet/'.$snippet_id);
}
}
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['snippet'] = $snippet;
//display the edit product form
$this->data['title'] = array(
'name' => 'title',
'type' => 'text',
'value' => $this->form_validation->set_value('title', $snippet['title']),
);
$this->load->view('dashboard/edit_snippet', $this->data);
}
}
heres the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
$query = $this->db->get('snippets');
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
}
heres the view:
<?php echo $message;?>
<?php $snippet_id = $snippet['id']; ?>
<?php echo form_open("mysnippets/edit_snippet/$snippet_id");?>
<?php echo form_input($title); ?>
<?php echo form_submit('submit', 'Submit');?>
<?php echo form_close(); ?>
is there a way i can restrict it so if another user tried to go to that url i can redirect them or show a error message
Something like this might work.
public function edit_snippet(snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
// this depends on what you are using for sessions;
// recommend you use db sessions
if($snippet->user_id != $this->session->userdata('user_id');)
{
redirect('/mysnippets');
}
else
{
//allow editing
You could check whether the id you are editing is the same as the session id provided when you have logged in.
it could be something like :
if ($snippet_id != $this->session->userdata('login_id'))
{
//redirect to another page
}
I would just add a line to the following function in the model:
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
//users can access only their own snippets
$this->db->where('user_id', $this->session->userdata('user_id'));
$query = $this->db->get('snippets');
return $query->row_array();
}
That prevents them from accessing the information, but I'd do something to prevent them from even being able to try in the first place, i.e. not giving them the choice.

Categories