CodeIgniter Forums
how to manage DB connections - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Installation & Setup (https://forum.codeigniter.com/forumdisplay.php?fid=9)
+--- Thread: how to manage DB connections (/showthread.php?tid=92737)



how to manage DB connections - PaulC - 04-10-2025

Hi If so how do  Team,
In my CI3 app I never worried about this because we autoloaded 'database' lib.
In CI4 it seems I now have to connect in my code - I have chosen the constructor of any Controller or Model where ever I need to access the database.
I am now aware that I could hit connection limits (currently 151 by default for mysql db)
A few (perhaps) obvious questions:
1) If I make a connection in a controller and the user session redirects to another controller will the $db persist for the session or do I open a second etc connection?
2) Should I check for an existing connection in each constructor and either proceed or open a new connection as appropriate? If so how please?
3) Another potential strategy would be to force a disconnect on completion of my db interation. If so how please?
4) I quite like the freeQuery() call. Is this recommended to optimise memory as lng as you don't need the cached result?
I have read the upgrade notes carefully but haven't found those nuggets yet.
Appreciate any thoughts and guidance.
TIA, Paul

Sorry typo in first line ...groan


RE: how to manage DB connections - printerdriversupport - 04-11-2025

Hey Paul, in CI4, each request is fresh—DB connections don’t persist between controllers or sessions. Just use db_connect() and CI4 will reuse the same connection for that request. No need to manually check or close unless you're doing something heavy—then $db->close() helps. And yeah, freeResult() is good for saving memory if you don’t need the result anymore.


RE: how to manage DB connections - SergioDaroca - 04-15-2025

Knowing if the data/state is ready is often not easy. Codeigniter 4 has an event system you could use, to trigger things when you want them: https://codeigniter4.github.io/userguide/extending/events.html
I reduced my db calls to the minimum using the resultArray to filter data usign lookup tables created with array_column or array_filter:

// Create a URI => ID mapping
$lookup = array_column($data, 'id', 'uri');
if (isset($lookup['/about'])) {
$id = $lookup['/about'];
echo $id;
}

or when you need all data:
$result = array_filter($data, function($item) use ($searchUri) {
return $item['uri'] === $searchUri;
});

if (!empty($result)) {
$id = reset($result)['id'];
echo $id; // Output: 2
}
good hunting!