Welcome Guest, Not a member yet? Register   Sign In
Making $db available globally
#1

Taken from https://codeigniter.com/user_guide/datab...cting.html



Quote:You can connect to your database by adding this line of code in any function where it is needed, or in your class constructor to make the database available globally in that class.


When i do exactly that:

Code:
<?php

namespace App\Models\Admin;

use CodeIgniter\Model;

class AccessModel extends Model
{

  function __construct()
  {
    $db = \Config\Database::connect();
  }
 
  // This function does the log in and stores the admin info from to DB to a session array
  public function login($username,$password)
  {
    $query  = $db->query('SELECT password, email FROM admin');
    $results = $query->getResult();
    var_dump($results);die();
  }
i get the following error:

ErrorException

Undefined variable $db


I also tried adding it into the BaseController which im trying to use as Ci3's version of an autoloader but i get the same error
Code:
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);     

        // Preload any models, libraries, etc, here.
        helper('form');
        $db = \Config\Database::connect();


Kindly point me in the right direction.
Reply


Messages In This Thread
Making $db available globally - by CodingInCodeigniter - 10-15-2021, 09:53 AM
RE: Making $db available globally - by sr13579 - 10-16-2021, 04:50 PM
RE: Making $db available globally - by iRedds - 10-16-2021, 09:11 PM



Theme © iAndrew 2016 - Forum software by © MyBB