controller/model does not return true result - php

I'm trying to update result in the database.The Update query is working fine, values are getting updated but controller show else results always.
Below code
base Controller
#update/save in model
$data = ['twitter_link' => $this->input->post('twitter_link')];
if($this->Restaurant_admin->update_site_settings($data,'setting_id',1,'site_setting')){
$this->session->set_flashdata("update_success_twitter","Twitter link updated successfully.");
redirect('admin/Entry/basic_table');
}else{
$this->session->set_flashdata("update_success_twitter","Something went wrong data not saved.");
redirect('admin/Entry/basic_table');
}
Restaurant_admin Model
public function update_site_settings($data,$where_cond,$value,$table_name)
{
$this->db->set($data);
$this->db->where($where_cond,$value);
$this->db->update($table_name,$data);
}
#update_site_settings

In model update_site_settings function check the query is executed or not, If executed successfully return true else return false
public function update_site_settings($data,$where_cond,$value,$table_name)
{
$this->db->set($data);
$this->db->where($where_cond,$value);
if($this->db->update($table_name,$data))
{
return true;
}
else
{
return false;
}
}

Related

how to run two statements in one funcation

I'm trying to delete from two tables using one function.
Controller code:
public function userdelete()
{
$u_id = $this->uri->segment(3);
$lr_id = $this->uri->segment(3);
$returndata = $this->user_model->user_delete($u_id, $lr_id);
if($returndata) {
$this->session->set_flashdata('successmessage', 'user deleted successfully..');
redirect('users');
} else {
$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
redirect('users');
}
}
Modle code:
public function user_delete($lr_id, $u_id ) {
return $this->db->delete('login_roles',['lr_id'=>$lr_id]);
return $this->db->delete('login',['u_id'=>$u_id]);
}
I'm able to delete only from the first table but not the other one. this is working :
return $this->db->delete('login_roles',['lr_id'=>$lr_id]); but not return $this->db->delete('login',['u_id'=>$u_id]);.
As said in the comment you have to remove the first return.
You should compute the two results :
public function user_delete($lr_id, $u_id ) {
$delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
$delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
return ($delete1Response AND $delete2Response);
}
It will returns true only if both are deleted
You even can go further and :
public function user_delete($lr_id, $u_id ) {
$delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
$delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
return (object)array('role' => $delete1Response, 'user' => $delete2Response);
}
Then you can access to data like that :
$response = user_delete(...);
if ($response->role AND $response->user) {
// All fine
} else {
// One or both failed.
// Display error or do something
}
It never reaches the second $this->db->delete since its returns after executing the first one. Try:
public function user_delete($lr_id, $u_id ) {
if($this->db->delete('login_roles',['lr_id'=>$lr_id])){
//success, try the next one
return $this->db->delete('login',['u_id'=>$u_id]);
}
//failed
return false;
}

my values on one column wont update immediately after inserting data, but after refresh the values shows up

after I inserting data, what shows on the column table "Jumlah Hasil Perah" shows '0'. but after refreshing the browser, the value shows up the result.
here's the code
Model (m_hasilperah):
public function jumlahPerahSapi($id)
{
$this->db->select('hasilPerahPagi, hasilPerahSore');
$this->db->where('idSapi', $id);
$cek = $this->db->get('tb_hasilperah');
if ($cek) {
$this->db->set('jumlahPerah', "hasilPerahPagi + hasilPerahSore", FALSE);
$this->db->where('idSapi', $id);
$this->db->update('tb_hasilperah');
}
return false;
}
Controller
public function tambahHasilPerah(){
$idSapi = $this->input->post('idSapi');
$tglPerah = $this->input->post('tglPerah');
$hasilPerahPagi = $this->input->post('hasilPerahPagi');
$hasilPerahSore = $this->input->post('hasilPerahSore');
$jumlahPerah = $this->m_hasilperah->jumlahPerahSapi($idSapi);;
$data =
[
'idSapi' => $idSapi,
'tglPerah' => $tglPerah,
'hasilPerahPagi' => $hasilPerahPagi,
'hasilPerahSore' => $hasilPerahSore,
'jumlahPerah' => $jumlahPerah
];
$insert = $this->m_hasilperah->tambahHasilPerahModel($data, $idSapi);
if ($insert) {
redirect('C_hasilperah/tampilHasilPerah/' . $idSapi, 'refresh');
} else {
echo 'gagal';
}
}
Screenshot:
View after insert(before manual refresh)
View after manual refresh
Your Model method jumlahPerahSapi() every time returned false. Even if after the data update. Please look into this.
Your Model function jumlahPerahSapi($id) is always return false even inserted successfully in DB.
So This is not run redirect('C_hasilperah/tampilHasilPerah/' . $idSapi, 'refresh');
Every time run echo 'gagal';
Modify the model function as follows.
public function jumlahPerahSapi($id)
{
$this->db->select('hasilPerahPagi, hasilPerahSore');
$this->db->where('idSapi', $id);
$cek = $this->db->get('tb_hasilperah');
if ($cek) {
$this->db->set('jumlahPerah', "hasilPerahPagi + hasilPerahSore", FALSE);
$this->db->where('idSapi', $id);
$this->db->update('tb_hasilperah');
return true;
}
return false;
}

Laravel exists() function keeps returning false when it does exist

i'm not sure what im doing wrong but every time i click the like button it turns up false
Im using laravel 5.5
it clearly works it when i pass in the post id, whenever i click it.
http://127.0.0.1:8000/post/144/islikedbyme
my console log shows no errors, the like button works but the isLikedByMe function keeps rendering
false
in the network log and i don't know why. It works look at the datebase
PostController.php
public function isLikedByMe($id)
{
$post = Post::find($id);
if (Like::whereUserId(auth()->user()->id)->wherePostId($post)->exists()){
return 'true';
}
return 'false';
}
Route
Route::get('post/{id}/islikedbyme', 'PostController#isLikedByMe');
Route::post('post/like/{post}', 'PostController#like');
Main.js
$scope.like = function(post) {
$http.post('/post/like/'+ post.id).then(function(result) {
$scope.getLike(post);
});
};
$scope.getLike = function(post){
$http.get('/post/'+ post.id +'/islikedbyme').then(function(result) {
if (result == 'true') {
$scope.like_btn_text = "Like";
} else {
$scope.like_btn_text = "Unlike";
}
});
}
Because it's removed, if you want even the removed ones do it like this :
public function isLikedByMe($id)
{
$post = Post::find($id);
if (Like::withTrashed()
->whereUserId(auth()->user()->id)
->wherePostId($post->id)->exists()){
return 'true';
}
return 'false';
}
Or even better if you don't want the post insatance you can do it like this :
public function isLikedByMe($id)
{
if (Like::withTrashed()
->whereUserId(auth()->user()->id)
->wherePostId($id)->exists()){
return 'true';
}
return 'false';
}
Try something like below :
public function isLikedByMe($id) {
$post = Post::find($id);
$is_like = Like::where(['user_id' => auth()->user()->id, 'post_id' => $post->post_id])->exists();
if ($is_like) {
return 'true';
}
return 'false';
}

Codeigniter how to use transactions

I have read up on some stuff about transactions in Codeigniter. I have implemented them in my code and was wondering if someone could take a look and see if I am going in the right direction? So far I have not encountered any database issues but I want to make sure I have implemented transactions correctly.
In my code, I create the user details first and get the ID, then I insert that ID into the user accounts table.
Controller
if($this->form_validation->run()==false){
$this->index();
}else{
$password = md5($password);
$package = array(
'first_name'=>$first_name,
'last_name'=>$last_name,
'email'=>$email,
'client_id'=>$client_id,
'date_of_birth'=>$date_of_birth,
'phone_number'=>$phone_number,
'address'=>$address,
'country'=>$country,
'created_on'=>$this->get_date(),
'updated_on'=>$this->get_date()
);
if($this->AccountModel->user_account_exists($email)){
$this->session->set_flashdata('Error',"Account already exists");
redirect('/Register');
}else{
$this->db->trans_start();
$id = $this->AccountModel->create_person($package);
$error = $this->db->error();
$this->db->trans_complete();
$expiration_date = date('Y-m-d', strtotime($this->get_date() . "+1 month") );
if($this->db->trans_status()===false){
$this->index();
}else{
$account = array(
'username'=>$email,
'password'=>$password,
'user_type'=>'user',
'person_id'=>$id,
'is_active'=>true,
'created_on'=>$this->get_date(),
'updated_on'=>$this->get_date(),
'expires_on'=>$expiration_date,
'status'=>'active'
);
$this->db->trans_start();
$id = $this->AccountModel->create_user_account($account);
$error = $this->db->error();
$this->db->trans_complete();
if($this->db->trans_status()===false){
$this->index();
}else{
$this->session->set_flashdata('Success','Account has been created');
redirect('/Login');
}
}
}
if($error!=''){
$this->session->set_flashdata('Error',$error["message"]);
redirect('/Register');
}
}
Model
public function create_user_account($input){
$this->db->insert('user_accounts',$input);
return $this->db->insert_id();
}
public function create_person($input){
$this->db->insert('person',$input);
return $this->db->insert_id();
}
Hope someone can help me with this
The reason for transactions is to perform multiple db query operations and if any operations fail undo any that have already taken place.
You are only performing one operation within your transaction block so transactions are pointless. Other than that, you've got the idea.
In your case where you are only using db->insert() you can easily check the results and respond accordingly. db->insert() returns either true or false. If the return is false, get the error and set it into flashdata. Otherwise, go on with your work.
As #Topjka say, transactions should be in the model code.
Here's a sample model
class Some_model extends CI_Model
{
public function save_stuff($data)
{
//let's assume $data has values for two different tables
$newInfo = $data['newStuff'];
$updateInfo = $data['oldStuff'];
$this->db->trans_start();
$this->db->insert('other_table', $newInfo);
$this->db->update('one_table', $updateInfo);
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$this->set_flash_error();
return FALSE;
}
return TRUE; //everything worked
}
public function set_flash_error()
{
$error = $this->db->error();
$this->session->set_flashdata('Error', $error["message"]);
}
}
Transactions are justified above because we do two db ops and if the either fails we don't want any changes to the db made.
Using the model/method in the controller
if($this->some_model->save_stuff($the_stuff) === FALSE)
{
redirect('/wherever');
}
//All OK, proceed
//do other controller things

Redirecting not working in codeigniter

So here's what I want to do. I want to check if the userid in segment(3) exist or else it will redirect somewhere instead of still loading the view with an error.
Here's the example url
http://localhost/ems/edit_user/edit_user_main/1001
Now if I try to edit the userid in segment(3) and intentionally put an invalid userid, it still loads the view and i don't know why
Here's my function
public function edit_user_main(){
$id = $this->uri->segment(3);
$check = $this->get_data->check_if_exist($id);
if($check) {
$data['title'] = 'Edit User';
$data['id'] = $this->session->userdata('usertoedit');
$this->load->model('accounts/get_data');
$item = $this->get_data->get_user($id);
$data['user'] = $item[0];
$data['main_content'] = 'edit_user/edit_user_main';
$this->load->view('includes/template', $data);
} else {
redirect('admin/adminuser');
}
}
Here's the model
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query) {
return TRUE;
} else {
return FALSE;
}
}
There is no problem with the fetching of data.
The problem is even if the userid doesn't exist, the view is still loading but with an error coz there's no data for that userID. It's not redirecting,
I tried using print_r and it working fine, the value of the $check is 1 when there's a valid userID.
Hope someone can help me with this. Thank you
With your function it will always return true because the statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always execute,So you need to check query is returning any result row or not with the statement
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
Try this..
With the function it will always return true because the following statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always be execute, So need to check query is returning any result row or not
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
And load heper as:-
$this->load->helper('url');
before the redirection

Categories