php - Efficiently use mysqli in object oriented setting -
i have come conclusion using mysqli in oo approach better procedural approach. (source: why object oriented php mysqli better procedural approach?). i'm not quite sure if doing more efficient doing before.
i have function runs sql queries. block of code looked like:
database connection:
function connectdb(){ $con = mysqli_connect(server, username, password, database); return $con; }
query function:
function executequery($payload){ $con = connectdb; $result = mysqli_query($con, $payload); return $result; }
as can see, that's not efficient because i'm creating new database connection every time executequery
called. figured i'd try using oop.
database connection (oop):
function connectdb(){ $con = new mysqli(server, username, password, database); return $con; }
database query (oop):
function executequery($payload){ $con = connectdb(); $result = $con->query($payload); return $result; }
now me, seems doing wrong. each time query called re-instantiating mysqli
class , assume mean's making database connection.
so how do , efficiently?
so how do , efficiently?
this has nothing using mysqli in procedural versus oop way.
what has following line:
$con = connectdb();
this recreate database connection on every query. which, noted, not efficient.
there many ways solve this. example:
- use
mysqli
class directly. - pass
$con
executequery()
(dependency injection) - create db class both
connectdb()
,executequery()
.
i use mysqli
directly see no reason wrap native class. create connection object globally (in config file) , use dependency injection when other objects/functions need it.
Comments
Post a Comment