how to prevent access by status - codeigniter

i have code like this
my model:
function get_status()
{
$nik=$this->session->userdata('nik');
$this->db->select('*');
$this->db->where('nik',$nik);
$this->db->from('t_trx_activity');
$query= $this->db->get();
return $query->result();
}
my controller:
public function input()
{
$status = $this->activity->get_status();
if ($status->status ==1) {
redirect ('activity');
} else {
$data = array(
'title' => 'Activity',
'breadcrumb'=> 'Input Activity'
);
$this->load->view ( 'default', $data );
}
}
my problem when status=1 site can access,i hope i can't access site and redirect other site.
how to prevent acccess when status=1?

What value your storing in status field in 't_trx_activity' table?
By default if your storing it is as '1' then condition is always true and it will be redirected.

Related

Single column not being updated in laravel 5

I am tying to update a single column of a table messages and I have the following code:
public function messageSeen(Request $request){
$data = Message::find($request->id);
$success = Message::where('id', $request->id)->update(array('is_seen' => 1));
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
I am getting the response Data not updated. If you question, does the column is_seen exists? then yes it does. Even I tried fetching the data having id $request->id, it gives the proper data. I wonder why is the data not being updated? Am I doing right thing to update column or is there an way out to update column in different way?
I tried the other way like the following:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
dd($result->message);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result->message;
$data['user_id'] = $result->user_id;
$data['conversation_id'] = $result->conversation_id;
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
But here I am getting unexpected thing with this method. Here I am being able to do dd($result) and being able to get data like this:
#attributes: array:9 [
"id" => 22
"message" => "How are you?\r\n"
"is_seen" => 0
"deleted_from_sender" => 0
"deleted_from_receiver" => 0
"user_id" => 2
"conversation_id" => 1
"created_at" => "2019-09-29 03:42:39"
"updated_at" => "2019-09-29 03:42:39"
]
however, if I tried to do dd($result->message) then I get null! What am I doing wrong?
I tried the following code:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result[0]['message'];
$data['user_id'] = $result[0]['user_id'];
$data['conversation_id'] = $result[0]['conversation_id'];
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
and it worked but instead of updating it is adding new column when the message is seen. But first I don't understand why do I have to do $result[0]['key'] in the first place.
You need to specify which fields in your table can be mass assigned, by adding or updating the $fillable property of your model:
protected $fillable = [..., 'is_seen', 'message', ...];
This is required for the create() and update() methods, as those accept "mass" variables in the array you pass in. Whereas with save() you have to manually, explicitly, assign the properties on the model, so there is no risk of accidentally saving something you didn't mean to. And this is exactly the behaviour you are seeing - update() is not working, but save() is.
You should try this
public function messageSeen(Request $request) {
$input = Request::all();
$data = Message::find($input['id']);
if (!empty($data)) {
$update = array();
$update['is_seen'] = 1;
$success = Message::where('id', $input['id'])->update($update);
if ($success) {
return response()->json(['status' => 'success'], 200);
} else {
return response()->json(['status' => 'Something went wrong'], 400);
}
} else {
return response()->json(['status' => 'Data not updated'], 404);
}
}
Value depends on data type of is_seen are string or integer

how to check if username already exists in codeigniter my error

My controler cod is:
function register()
{
if(isset($_POST['register'])){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if($this->form_validation->run () == true){
echo 'Form Validate';
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=>strtoupper(hash('whirlpool',$_POST['password']))
);
$this->db->insert('accounts',$data);
$this->load->model("usuarios_model");
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
}
}
$this->load->view("painel/register");
}
[![enter image description here][2]][2]
It registers an user even though the username already exists.
Where is the mistake?
You can use is_unique rule in your form_validation library.
$this->form_validation->set_rules('username','Username','required|is_unique[table.column]');
You have mistake in your model in where condition it will be small later of username but you used Username.
use this code in your model.
function check_user_exist($username){
$this->db->wehre('username',$username);
$this-db->from('accounts');
$query= $this->db->get();
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}
and also controller data insert after user check:
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
You can easily achieve this using call_back function in validation. From Codeigniter Docs
Controller
function register() {
if ($this->input->post('register')) {
$this->form_validation->set_rules('username','Username','required|callback_checkUserName');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if ($this->form_validation->run() == true) {
$data = array(
'username '=> $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => strtoupper(hash('whirlpool', $this->input->post('password')))
);
$this->db->insert('accounts',$data);
echo 'success';
exit();
} else {
echo validation_errors(); die; // check errors
}
}
$this->load->view("painel/register");
}
// call back validate function
function checkUserName($userName){
if ($this->usuarios_model->checkUserexist($userName) == false) {
return true;
} else {
$this->form_validation->set_message('checkUserName', 'This userName already exist!');
return false;
}
}
MODEL
function checkUserexist($userName) {
$this->db->where('username', $userName);
$this-db->from('accounts');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return true;
}
return false;
}
This my code which I used in one of my projects replace the words with your code:
$this->form_validation->set_rules('companyname','Company Name','trim|required|callback_companyname_exist');
Here is above callback function:
function companyname_exist($str) {
$this->db->where('company_name', $str);
$this->db->where('user_type','Shop');
$prod = $this->db->get('grs_user');
if ($prod->row()) {
$this->form_validation->set_message('companyname_exist', 'This Company name is already Available.');
return FALSE;
} else
return TRUE;
}
You can used this for already register email check also.

Codeigniter multiple parameter on update

I am copying this code in Codeigniter official docs, but I don't know why this will throw an error
public function acceptChangeRequest($id,$data1,$accept) {
$data = array(
'status' => $accept,
'approve_by' => $data1,
);
$this->db->where('id', $id);
$this->db->update('change_request',$data);
//return true;
}
Error Number: 1054
Unknown column 'Array' in 'field list'
UPDATE change_request SET status = 'Y', approve_by = Array WHERE id = '22'
It sounds wierd since this code works in my other function. Any idea?
Read The Documentation Clearly
Read About Update Records In Codeigniter
Here IS Demo Function For You
public function updateBasic($data,$user_id){
$userData=array(
'marital_status'=>$data['marital_status'],
'country'=>$data['stateofresidence'],
'city'=>$data['city'],
'caste'=>$data['caste'],
'residential_status'=>$data['residencystatus']
);
$this->db->WHERE('user_id',$user_id)->update('basic_profile',$userData);
return true;
}
You Must Check Through Print_r();what Is coming To your Function In Your Case $data1 Is Coming In the From OF array You Must Extract The Array To Update The Record
Use this function in your model to update the record.
public function acceptChangeRequest($where, $table, $data){
$this->db->where($where);
$this->db->update($table, $data);
return $this->db->affected_rows() > 0;
}
use this code in your controller.
$where = array('id'=>$id);
$data = array(
'status' => $accept,
'approve_by' => $data1,
);
$this->User_model->update($where,'table_name',$data);
What is in your $data1 variable? I can see that it's an array, and that is the problem.
If your $data1 stores indexes like in your table's row, than this is the possible solution for you:
public function acceptChangeRequest($id,$data1,$accept) {
$data1["status"] = $accept;
$this->db->where('id', $id);
$this->db->update('change_request', $data1);
return true;
}
But if your $data1 variable stores only the approve_by information, than your possible solution is:
public function acceptChangeRequest($id,$data1,$accept) {
$data = array(
'status' => $accept,
'approve_by' => $data1["approve_by"]
);
$this->db->where('id', $id);
$this->db->update('change_request', $data);
return true;
}
First of all, you need to know what you expect from $data1, than you can move forward to the solution.
You can see your $data1 variable in your Controller's function:
print "<pre>";
print_r($data1);
print "<pre>";
die();

Only show user_id and username after log in in codeigniter

I have a login and registration system in codeignitor.
This is my controller -
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
//$data['username'] = $session_data['username'];
$data = array(
'user_id'=>$session_data['user_id'],
'username'=>$session_data['username'],
'firstname'=>$session_data['firstname'],
'lastname'=>$session_data['lastname']
);
$this->load->view('home_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this code only show me the user_id and username. but not showing the firstname and lastname. Please help me ...
Considering that you have set your session like this,
$data = array(
'user_id'=>id,
'username'=>"name",
'logged_in'=>1,
);
$this->session->set_userdata($data);
To access values from session,
$this->session->userdata("name of session variable");
In your case,
$this->session->userdata("user_id");// for user id
$this->session->userdata("user_name");// for user name
if($result) {
$sess_array = array();
foreach($result as $row) {
$sess_array = array(
'user_id' => $row->user_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;
}
In your above given code I can't find the firstname in session setting. But you are trying to get firstname then how will the code provide you the firstname.

codeigniter error using JOIN to select single row

Im trying to get joins to work when selecting a single row. here is my code:
model:
function view($id) {
$this->db->select('c.name
,c.phone
,c.active
,c.website
,c.date_acquired
,con.firstName');
$this->db->from('company c');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->row_array();
controller:
public function view($id)
{
$this->load->model('Company_model');
$data['data']= $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
the error im getting is:
Fatal error: Call to a member function row_array() on a non-object in
/home/techf/public_html/application/models/company_model.php on line
35
and line 35 in the above code is:
$query = $this->db->get()
is this not correct when dealing with joins and a row array?
**
edit 1
**:
Here is my controller:
public function view($id)
{
$this->load->model('Company_model');
$data = $this->Company_model->view($id)->row();
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
and my model:
function view($id) {
$this->db->select('*');
$this->db->from('company');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
return $this->db->get('company');
}
but now im am getting error:
Fatal error: Call to a member function row() on a non-object in
/home/techf/public_html/application/controllers/company.php on line 21
Here you go model code
public function get_joins($table,$value,$joins,$where,$order_by,$order)
{
$this->db->select($value);
if (is_array($joins) && count($joins) > 0)
{
foreach($joins as $k => $v)
{
$this->db->join($v['table'], $v['condition'], $v['jointype']);
}
}
$this->db->order_by($order_by,$order);
$this->db->where($where);
return $this->db->get($table);
}
and in your controller aceess it like
$value=('restaurantorders.*,restaurant.Name,restaurant.CurrencyId,currency.*,orderpaymentdetail.Gateway ');
$joins = array
(
array
(
'table' => 'tk_restaurant',
'condition' => 'restaurant.Id = restaurantorders.RestaurantId',
'jointype' => 'inner'
),
array
(
'table' => 'tk_currency',
'condition' => 'restaurant.CurrencyId = currency.Id',
'jointype' => 'inner'
),
array
(
'table' => 'tk_orderpaymentdetail',
'condition' => 'restaurantorders.Id = orderpaymentdetail.OrderId',
'jointype' => 'inner'
),
);
$data['order_detail'] = $this->general_model->get_joins($data['tbl'],$value,$joins,array('OrderStatus'=>'Confirm','restaurantorders.Id'=>$orderid),'restaurantorders.Id','desc')->row();
note that on the model i test first if num_rows() is greater than 1 before sending on the row and if not return false.
Note that on my this->db->get i removed the name of the table, because you already added it on the from method.
$this->db->select('*')
->from('company c');
->join('contacts con','c.primary_contact = con.id','left');
->where('id', $id);
$query = $this->db->get();
return $query->num_rows() >= 1 ? $query->row() : FALSE;
on your COntroller
on on the data variable you forgot to add a key, this will be used when you access the variable/object on you're view, example is $data['contacts']
public function view($id)
{
$this->load->model('Company_model');
$data['contacts'] = $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
on your VIEWS
access the contacts key that you assigned earlier on you're controller.
<?
if(!empty($contacts))
{
print_r($contacts);
}else{
echo 'No data';
}
?>
to show the structure of your query on a standard MySQL query
you could comment out the return on you're model and add this snippets of code just after the $this->db->get() method.
echo $this->db->last_query();
die();
This will echo out what query was made, and you can run it on phpmyadmin and compare if the values returned are right.
can you try it like this maybe?
model: (i'm not sure in which table is id and in which primary_contact, so change that if i made a mistake)
function view($id) {
$this->db->join('contacts','company.primary_contact = contacts.id','left')
->where('id', $id);
$query = $this->db->get('company');
return $query->row();
}
in controller call it like this:
$data['result'] = $this->company_model->view($id);
then access object in view:
<?=$result->id?> (etc.)

Resources