【问题标题】:CodeIgniter4 db->save() methodCodeIgniter4 db->save() 方法
【发布时间】:2020-11-22 12:23:26
【问题描述】:

我在 CI4 中进行了一些尝试,但在将数据保存到数据库时遇到了问题。

我正在尝试如下:

use App\Models\UserModel;                                                                          
     ...                                                                   
       $model = new UserModel();
            $newUser = [                    
                'firstname' => $this->request->getVar('firstname'),
                'lastname' => $this->request->getVar('lastname'),
                'email' => $this->request->getVar('email'),
                'password' => $this->request->getVar('password')
            ];
            $model->save( $newUser );

显示的错误是: 列数与第 1 行的值数不匹配

如果我们查看查询参数,它会生成一个没有参数的查询:

$query  INSERT INTO `users` () VALUES ('')

用户表:

  CREATE TABLE IF NOT EXISTS `users` (   `id` int(11) NOT NULL AUTO_INCREMENT, 
      `firstname` varchar(60) COLLATE utf8mb4_general_ci NOT NULL,
      `lastname` varchar(60) COLLATE utf8mb4_general_ci NOT NULL,
      `email` varchar(60) COLLATE utf8mb4_general_ci NOT NULL,
      `password` varchar(60) COLLATE utf8mb4_general_ci NOT NULL,
      `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

用户模型

<?php 

namespace App\Models;
use CodeIgniter\Model;


class UserModel extends Model
{
    protected $table      = 'users';
    protected $primaryKey = 'id';

    protected $returnType = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['firstname', 'lastname', 'email', 'password', 'updated_at'];

    protected $useTimestamps = false;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = '';

    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;

    protected $beforeInsert = ['beforeInsert'];
    protected $beforeUpdate = ['beforeUpdate'];


    protected function beforeInsert( array $data )
    {
        $this->_hashPassword( $data );
    }

    protected function beforeUpdate( array $data )
    {
        $this->_hashPassword( $data );
    }

    protected function _hashPassword( array $data )
    {
        if( isset($data['data']['password']))
            $data['data']['password'] = password_hash( $data['data']['password'] , PASSWORD_DEFAULT);

            return $data;
    }
}

【问题讨论】:

  • 这仅仅意味着你的 newUser 数据是空的。您还应该发布获取数据的方式。

标签: php database codeigniter-4


【解决方案1】:

感谢您的帮助,问题出在 DB 端口配置中,默认情况下,codeigniter 将其设为 3306,而在 wampServer 中,它由 MariaDB 使用,我只需将其更改为 3308 (MySqlDB) 即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2018-11-19
    相关资源
    最近更新 更多