Search code examples
phpcodeigniterquery-buildercodeigniter-4

Code Igniter 4 Error when showing table from database


I want to show all supplier records from my table to my view, but it always returning this error when I show the data with print_r although the table name and database is correct it wont show the table contents.

It always output this error :

object(CodeIgniter\Database\MySQLi\Result)#81 (8) { ["connID"]=> object(mysqli)#78 (18) { ["affected_rows"]=> int(6) ["client_info"]=> string(13) "mysqlnd 8.2.0" ["client_version"]=> int(80200) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["field_count"]=> int(3) ["host_info"]=> string(20) "localhost via TCP/IP" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=> string(15) "10.4.27-MariaDB" ["server_version"]=> int(100427) ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(115) ["warning_count"]=> int(0) } ["resultID"]=> object(mysqli_result)#80 (5) { ["current_field"]=> int(0) ["field_count"]=> int(3) ["lengths"]=> NULL ["num_rows"]=> int(6) ["type"]=> int(0) } ["resultArray"]=> array(0) { } ["resultObject"]=> array(0) { } ["customResultObject"]=> array(0) { } ["currentRow"]=> int(0) ["numRows":protected]=> NULL ["rowData"]=> NULL }

What did I do wrong ?

SupplierController :

<?php

namespace App\Controllers;

use App\Models\SupplierModel;
use CodeIgniter\API\ResponseTrait;

class SupplierController extends BaseController
{
    use ResponseTrait;
    function __construct()
    {
        $this->supplierModel = new SupplierModel();
    }
    public function index()
    {
        $model = new SupplierModel();
        $dataSupplier = $model->get();
        var_dump($dataSupplier);
        // return view('pages/Supplier');
    }
}

Supplier Model :

<?php

namespace APP\Models;

    use CodeIgniter\Model;
    use CodeIgniter\API\ResponseTrait;
    use CodeIgniter\Exceptions;
    use CodeIgniter\Exceptions\PageNotFoundException;
    use Exception;
    use CodeIgniter\Config\Database;
    
    class SupplierModel extends Model
    {
        use ResponseTrait;
        protected $table = 'supplier';
        protected $primaryKey = 'id';
        protected $allowedFields = ['name', 'vendor'];
   
        public function get()
        {
            $db = \Config\Database::connect();
            $builder = $db->table('supplier');
            $data = $builder->get();
            return $data;
        }
    }

Database and Table :

databasetable

.env contents :

env


Solution

  • You have to generate query results. Update your model get() function. Also Check this https://codeigniter.com/user_guide/database/results.html

       public function get()
        {
            $db = \Config\Database::connect();
            $builder = $db->table('supplier');
            $data = $builder->get()->getResult();
            return $data;
        }