简体   繁体   中英

Error Call to a member function getFieldNames() on null in codeigniter 4

I'm trying to get the columns name from "users" table in my database using detFieldNames function in codeigniter 4 but something went wrong. Here is the error: Error

Model class:

class UsersModel extends Model
{
    public function __construct()
    {
        $db = \Config\Database::connect();
        $this->builder = $db->table('users');
    }
function getColumns()
    {
        $names = $this->db->getFieldNames('users');
        foreach ($names as $field) {
            echo $field;
        }
        exit;
    }

You don't have to manually set/configure the "Query Builder object". Simply set the $table protected property on the model to represent the name of the database table.

UsersModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class UsersModel extends Model
{
    protected $table = "users";

    function getColumns(): array|false
    {
        return $this->db->getFieldNames($this->table);
    }
}

UserController.php

// ...

$columns = (new \App\Models\UsersModel)->getColumns();

foreach ($columns as $column) {
   echo $column;
}

Addendum

You could alternatively just use the db_connect() helper method to get the default "database connection" . Ie:

$names = db_connect()->getFieldNames("users")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM