• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using AES_ENCRYPT in model

#1
I am trying CI4 4.0.0-alpha.1 and I encounter something that does not make sense to me. 

I have a user model and want to use AES_ENCRYPT in my sql query.

Solution 1 works, the password is encrypted. Solution 2 doesn't. It stores the password as AES_ENCRYPT('dasdsad','1234')

Is this a bug or is there something I do not understand correctly?

Solution 1 works:

PHP Code:
class UserModel extends \CodeIgniter\Model
{
    protected 
$table 'users';

    public function 
insert_user($data$aes_key)
    {
        
$builder $this->db->table$this->table );

        
$builder->set('user_pwd'"AES_ENCRYPT('{$data['password']}','{$aes_key}')"FALSE);
        
$builder->set('user_name'$data['name'], TRUE);
        
$builder->set('user_email'$data['email'], TRUE);

        
$builder->insert();
    }



Solution 2 doesn't work:

PHP Code:
class UserModel extends \CodeIgniter\Model
{
    protected 
$table 'users';

    public function 
insert_user($data$aes_key)
    {
        
$this->set('user_pwd'"AES_ENCRYPT('{$data['password']}','{$aes_key}')"FALSE);
        
$this->set('user_name'$data['name'], TRUE);
        
$this->set('user_email'$data['email'], TRUE);

        
$this->insert();
    }

Reply

#2
What is $this in second solution??
Reply

#3
The set() method you're trying to use is part of the Query Builder, not part of the model itself. The Model provides some magic that allows most of the commands to be intermingled, but you must realize there's still a difference.

In order to get a copy of the Query Builder, at some point you must call $this->builder(), which returns a copy set to the current table, or manually via [b]$this->db->table('x')[\b]. In the first version you're building it manually so it works. The second one the model class doesn't have the knowledge to do it correctly for you.

The best bet is to view the model as full of a bunch of convenience methods, which is what it is. Any query builder methods you use are modifiers to those convenience methods. The model isn't a replacement for the Query Builder.

Hope that helps.
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply

#4
@Piotr: $this is the instance of the UserModel.

I overlooked the $this->builder in the documentation.

The help for the Model->set() function states: Captures the builder's set() method so that we can validate the data here.

Based on that I had the impression that I was already dealing with the builder. But that turns out to be wrong.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.