CodeIgniter showing different menu using If statement - php

I have an error in the variable when I try to get the value it says it was undefined While I have already stored the session of the variable "$level" and sent it to the view but the condition of the variable become undefined, is there anything wrong with the code?
The variable that I get is from the login. Also I have tried to call the $level and it work
I have tried to use foreach and non foreach method still none of these are working
View.php
<?php if($level->level == '1') ?>
<p>Number 1</p>
<?php if($level->level == '2') ?>
<p>Number 2</p>
admin.php
function index(){
$level = $this->session->userdata('level');
$this->load->view('view',$level);
}
Login.php
public function do_login()
{
$u = $this->input->post("user");
$p = md5($this->input->post("pass"));
$cari = $this->model_pesawat->cek_login($u, $p)->row();
$hitung = $this->model_pesawat->cek_login($u, $p)->num_rows();
if ($hitung > 0) {
$data = array('admin_id' => $cari->no_user ,
'admin_user' => $cari->username,
'admin_nama' => $cari->nama,
'level' => $cari->level,
'admin_valid' => TRUE
);
$this->session->set_userdata($data);
redirect('admin','refresh');
}else{
echo "maaf username atau password salah";
}
}
I want the result the if statement will show different value in the view depending on the $level of the user

You need to pass array to the CodeIginter view.
And the array's keys will be used as individual elements in view.
Its similar to extract() function.
So, you should pass $data and add $level into it.
$data['level'] = $level;
$this->load->view('view', $data);
In your view, you can access $level from Controller as $level.
No need to care for $data

In view you can directly use session variable, no need to pass from controller
<p>Number 1</p>
<?php if($this->session->userdata('level') == '2') ?>
<p>Number 2</p>

you should check data in session, whether it's getting stored or not.
echo "<pre>"; print_r($this->session->userdata());

Related

How to make a search in codeiginiter without "like" paramameter?

Model:
function search()
{
$cari=$this->db->query("select * from uhd_user_order where user_order_reference ");
return $cari->result();;
}
Controller:
function search_keyword()
{
$this->input->GET('cari', TRUE);
$beda['cari'] = $this->order_test_m->search();
$this->load->view('admin/a',$beda);
}
View:
<?php if(count($cari)>0){
foreach ($cari as $row => $test) {
}?>
<?= $test->sendername ?>
<?php
} ?>
I need to make a search, and the result of the view will show up if I put the right code only. Like, if I only search "s", the data from my database will not show up.
How can this be done?
I am not sure what you want, I have some questions about your code, but I can not comment yet. I have to guess what happend:
I think your code works as: Whenever the 'search' button is clicked, all of your user's name in your database will be displayed, right?
Because your model does not use the 'get' data to search in the database
//Your function does not recieve the search string.
//This function uses $string to search in the 'users' table, to finds the name field == $string, and returns only 'name' row.
function search($string){
$query = $this->db->select('name')
->where('name',$string)
->get('users');
//If the result is empty, return false, do nothing.
if($query->num_rows() === 0){
return false;
}
return $query->result();;
}
Controller
function search_keyword()
{
// Call search function with the input data.
// I think here will have some validation
//for example:
//if($this->form_validation->run() == false){
// $this->load->view('errors/error');
//}
$search_string = $this->input->GET('cari', TRUE);
$beda['cari'] = $this->order_test_m->search($search_string);
$this->load->view('admin/a',$beda);
}
View:
// This will ensure the ul will only display when $cari is not empty.
<?php if(count($cari)>0):?>
<ul>
<?php foreach($cari as $row):?>
<li><?php echo $row->name;?></li>
<?php endforeach;?>
</ul>
<?php endif; ?>>

In CodeIgniter how to pass data between loaded views

Let say we are loading two or more views in the same class method like so:
$this->load->view('header');
$this->load->view('body');
$this->load->view('footer');
and you decide to create a variable inside the head view ($cat_name) like this example:
<?php
foreach ($categories as $key => $value) {
$selected = FALSE;
if ($this->router->class == 'category' && $this->router->method == 'id' && $this->uri->segment(3) == $value->id) {
$cat_name = $value->name;
$selected = TRUE;
}
?>
<option value="<?= $value->id; ?>" <?= ($selected ? 'selected' : ''); ?>><?= $value->name; ?></option>
<?php } ?>
This needed a loop to get that variable.
I want to pass that variable ($cat_name) to the next view without redoing the loop, that is just a waste.
what I am trying to achieve is minimizing the number of loops.
instead of loading all of that in controller load it in your view
create new file, let say template
$this->load->view('template',$variable);
and in your template
//do the loop here
$this->load->view('header');
$this->load->view('body');
$this->load->view('footer')
You need to create model for generating selects if You want to save MVC in Your project. I know, that's looks strange, but it will help You many times after
Controller
// load model
$this->load->model('myselect_model');
// get array with marked element
$select_data = $this->myselect_model->setSelected($categories, $this->router->class, $this->router->method, $this->uri->segment(3));
// get filled html
$my_html_select = $this->load->view('select_tpl',array('select'=>$select_data),TRUE);
// use it at any controller
$this->load->vars(array('my_select'=>$my_html_select));
// some views
$this->load->view('header');
$this->load->view('body');
$this->load->view('footer');
Model 'myselect_model'
function setSelected($items, $uri_controller,$uri_method, $uri_value){
// createing temp array for our list
$tmp = array();
foreach($items as $key=>$value){
// appending item
$tmp['options'][$key] = $value;
if ($uri_controller == 'category' && $uri_method == 'id' && $uri_value == $value->id)
{
// saving selected for any reason to use after
$tmp['selected'] = array('name'=>$value->name, 'id'=>$value->id);
// marking this item as selected
$tmp['options'][$key]['selected'] = TRUE;
}
}
// returning completed array
return $tmp;
}
View 'select_tpl'
<?php if(!empty($select)){?>
<select>
<?php foreach($select['options'] as $option){?>
<option value="<?=$option->id?>"<?=(isset($option['selected']) && $option['selected']==TRUE ? " selected=\"selected\"" : "")?>><?=$option->name?></option>
<?php }
</select>
<?php } ?>
views/header
<body><?=$my_select?><i>template here</i>
views/body
<p>some html here and our select goes here-> <?=$my_select?></p>
You could try like this:
Create a model like so:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Custom_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
function printSelect(){
// Do some logic and looping here
$html = "<select><option>...</option></select>";
return $html
}
}
Then call that model from your views like so..
$this->custom_model->printSelect();
Remember to load the model first.
$this->load->model('path/to/your/model/folder/custom_model');
This way, every time you want to print your you can simply call that method from your view.
I hope this helps.

Using flashdata while posting same controller twice in Codeigniter

I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks
save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata
Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.

Codeigniter delete multiple rows with checkboxes

I'm trying to delete multiple private messages from my database by selecting multiple checkboxes in the inbox and clicking submit to delete. I have the code below but nothing happens. I'm not sure what I'm missing..
View:
<?php echo form_open('pm/remove_checked'); ?>
<?php foreach ($query as $row): ?>
<input type="checkbox" name="msg[]" value="<?php echo $row->id; ?>" />
<?php echo $row->from; ?>
<?php echo $row->subject; ?>
<?php echo date("m/d/Y",strtotime($row->msg_date)); ?>
<?php endforeach; ?>
<?php echo form_submit('delete', 'Delete'); ?>
</form>
Controller:
function remove_checked()
{
//validation rules
$this->form_validation->set_rules('msg[]', 'Private Message', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$data['query'] = $this->Pm_model->received_msg();
$this->load->view('pm/inbox', $data);
}
else //success
{
$checked_messages = $this->input->post('msg'); //selected messages
$this->Pm_model->delete_checked($checked_messages);
//redirect to inbox
}
}
Model:
function delete_checked($checked_messages)
{
$checked_messages = array();
foreach ($checked_messages as $msg_id):
$this->db->select('id');
$this->db->from('user_msg');
$this->db->where('id', $msg_id);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0) //if message exists
{
$this->db->where('id', $msg_id);
$this->db->where('recipient', $this->users->get_user_id()); //verify if recipient id is equal to logged in user id
$this->db->delete('user_msg');
}
else
{
return FALSE;
}
endforeach;
}
In your current delete_checked() method, you are returning FALSE as soon as the first message is "found" that doesn't exist, this will prevent the rest of the messages from being deleted as return will stop execution of the loop. If you want to do it this way, use continue instead and consider using transactions.
If you don't particularly care about generating individual errors for each message, your model function can be simplified a bit:
function delete_checked($message_ids)
{
$this->db
->where_in('id', $message_ids)
->where('recipient', $this->users->get_user_id())
->delete('user_msg');
return $this->db->affected_rows() > 0;
}
This will just attempt to delete the records. If they don't exist they will be ignored, and $this->db->affected_rows() should return the number of messages deleted. You can compare it to count($message_ids) if you want to ensure that all messages selected were deleted, or use this example method that only checks if at least one message was deleted. If the message doesn't exist, you don't need to delete it anyways.
All the stuff Chris Schmitz mentioned is correct and important as well, you have some very basic errors. You may want to cast to array instead of assigning $checked_messages to an empty array if you expect you may be passing a single id (integer or string) to this function. Like this:
$message_ids = (array) $message_ids;
You are assigning $checked_msg to the inputs that are checked, but then you are passing a different variable called $checked_messages to the model. You'll want to pass the $checked_msg var to the model.
Also, in your model, you are redeclaring the $checked_messages var and setting it to an empty array. You'll need to remove that otherwise it will overwrite the info you are passing to the method.

PHP data array variable not defined in view

I am using codeIgniter and I am trying to pass an array of data. I have written like this:
$data['username']="Dumbo";
I also wrote this:
$data['shouts']=$this->Musers->getShout(); // retrieve data from table
Then I write:
$this->load->view("welcome_message", $data);
In view page, I wrote:
<?php echo $username;
foreach ($shouts as $shout)
{
echo $shout->shout;
echo '<br>';
echo $shout->timeStamp;
}
?>
Problem is that while the view did retrieve data from table and display results in view page, an error came up for $data['username'] saying:
"Undefined variable: username"
Why is that? The $data['username'] is already defined! Or what did I do wrong?
<?php echo $data['username']; ?>
If you wrote this, the error will occur.
Correct way is to write like
<?php echo $username; ?>
'username' is the index in the data array, which is passed to the view using the load method
$this->load->view("welcome_message", $data);
If you need to pass an array...
$data['usernames'] = $username_array;
$this->load->view("welcome_message", $data);
Then in the view,
<?php print_r($usernames); ?>
In your view, do this..
$data = array();
$data['username'] = "something";
$data['shouts']=$this->Musers->getShout();

Categories