• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Database query in a controller method?

#1
Thumbs Up 
Every now and then I need to run a quick database query which doesn't really belong to any of the Models. Or even when setting a quick demo site, I need a quick and dirty way. In CI3, I could just do
Code:
$this->db->query();
Is there something like that available in CI4?

I thought of setting a private variable as below and then use it in any of the methods. I am wondering if there is any better way?

PHP Code:
class Home extends Controller
{
 private 
$db;
 
   public function __construct()
 
   {
 
       $this->db = \Config\Database::connect();
 
   }

 
   public function index()
 {
 
$query $this->db->query('SELECT name, title, email FROM my_table');
 
//process query info
 
 
return view('welcome_message');
 }


Reply

#2
What you did works perfectly fine. If you just need it in the one method, though, no need to set it at the class level.

Code:
$db = db_connect();
$query = $db->query('SELECT name, title, email FROM my_table');
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply

#3
Ok that's great to get that confirmation! Thank you @kilishan
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.