I am working on a control-panel for a VoIP program and I've been working on it for a while. It started off as a small project that I just did because it was fun, but over time I added more and more features and it has now become something quite complex.
I have a file called functions.php
and it contains functions for handling login-requests, fetching a users avatar, getting memberlists, etc. It also performs any SQL operations required to perform these functions.
What I have noticed over time is that this file has become quite big, and there is a lot of code that is repeated -- especially SQL operations.
Here is an example of my get_memberlist()
function:
function get_memberlist($mysqli, $start = 0, $stop = 10, $sortby = 'username', $order = 'desc', $filter = null) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
if ($sortby == 'nickname') $sortby = 'last_nickname';
if ($stmt = $mysqli->query("SELECT * FROM users WHERE (user_id LIKE '$filter' OR email LIKE '%$filter%' OR last_nickname LIKE '%$filter%' OR username LIKE '%$filter%') ORDER BY $sortby $order LIMIT $start , $stop")) {
if($stmt->num_rows != 0) {
$row = array();
while($r = $stmt->fetch_array(MYSQLI_ASSOC)) {
$row[] = $r;
}
return $row;
}
}
return $row;
}
}
which is also quite similar to my getServerLogs()
function:
function getServerLogs($mysqli, $limit, $start, $end, $query, $filter) {
if ($stmt = $mysqli->query("SELECT * FROM server_logs WHERE `date` >= $start AND `date` <= $end AND is_query = $query AND message LIKE '%$filter%' ORDER BY id DESC LIMIT $limit")) {
if($stmt->num_rows != 0) {
$row = array();
while($r = $stmt->fetch_array(MYSQLI_ASSOC)) {
$row[] = $r;
}
}
return $row;
}
}
This seems inefficient and has repetitive code.
So my question is this: From a design perspective, how should I write the various functions and how the database operations?
Should I separate functions from database operations and have just a few generic db functions to call? Perhaps the best approach is to just have a db-file and send the query to be performed as a parameter?
Thanks.
return $row
while no value was assigned to it (which happens only deeper inside those nested if/then). – thorsten müller Jun 22 at 10:01