CodeIgniter Forums
Unable to connect to the database. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Unable to connect to the database. (/showthread.php?tid=77548)



Unable to connect to the database. - jatinkr@12 - 09-15-2020

I did a fresh installation of codeigniter 4 on my machine locally. When i started to work with database, i put all my database configuration in ".env" file. Connection was successfully established between the app and phpMyAdmin. When i am trying to run any query using query() method, it shows me "unable to connect to database". Please help me resolving this, i've been stuck on this since last 3 days.

Here is my code from Controller Home.php:

<?php
namespace App\Controllers;
Use Config\Database;
class Home extends BaseController {
    public function index() {
        $db = Database::connect();
        $query = $db->query("SELECT * FROM `users`");
        $results = $query->getResult();
        var_dump($results);
}
}
?>


RE: Unable to connect to the database. - John_Betong - 09-15-2020

@jatinkr@12,

I followed the manual and connected without any problems?

http://codeigniter.com/user_guide/database/examples.html?highlight=database


RE: Unable to connect to the database. - T.O.M. - 09-15-2020

Alternatively you can use "db_connect()" method to get connect to your database https://codeigniter.com/user_guide/database/connecting.html?highlight=db_connect

BUT you shouldn't do it in Controller - all work with database must be organized in Models or Entities https://codeigniter.com/user_guide/models/index.html