PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 25, 2022

[FIXED] CakePHP 3 : returns true even if data is not fetched from database

 January 25, 2022     cakephp, cakephp-3.2, php     No comments   

Issue

I'm working in CakePHP 3.2. There is a table user_addresses from which I'm trying to fetch all records of an user

public function myFun()
{
    $this->loadModel('UserAddresses');
    $user_id = $this->Auth->user('id');
    $userAddresses = $this->UserAddresses->find('all', [
       'conditions' => [
           'user_id' => $user_id
       ]
    ]);
    if (empty($userAddresses)) {
       echo 'Hello';               // for testing only
    } else {
       echo 'World';
    }
}

To check it, I added myFun to controller's beforeFilter

$this->Auth->allow(['myFun']);

and this prints World instead of Hello since there is no data retrieved from database because if user is not logged in then $user_id must be empty.


Solution

First of all check if $user_id is available then and then call find() method.

public function myFun()
{
    $this->loadModel('UserAddresses');
    $user_id = $this->Auth->user('id');
    if(empty($user_id)){
        echo "Not able to access this method";
        die();
    }
    $userAddresses = $this->UserAddresses->find('all', [
       'conditions' => [
           'user_id' => $user_id
       ]
    ]);
    if (empty($userAddresses)) {
       echo 'Hello';               // for testing only
    } else {
       echo 'World';
    }
}


Answered By - Bhavin Solanki
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing