I've been moving over from PHP procedural programming to OOP. I have a mysql database with two tables with a 1 to many relationship and I need to display that information in a list. I have written the following code, although the code executes fine I really don't know if it's the best approach of if i'm still thinking 'procedurally'. I've prepared the following statement:
$stmt = $mysqli_conn->prepare("SELECT display_name,
display_department,
display_region,
group_concat(approach_name) as approaches,
group_concat(length) as lengths,
group_concat(ascent) as ascents,
group_concat(gradient) as gradients
FROM table1 LEFT JOIN table2
ON table1.col_name=table2.col_name
GROUP BY table1.col_name");
This is the PHP code that follows:
$stmt->execute();
$stmt->bind_result($display_name, $display_department, $display_region, $approaches, $lengths, $ascents, $gradients);
while($stmt->fetch()) {
echo $display_name. ' | '.$display_department.' | '.$display_region.'<br>';
$arr_approaches = explode(',', $approaches);
$arr_lengths = explode(',', $lengths);
$arr_ascents = explode(',', $ascents);
$arr_gradients = explode(',', $gradients);
$arrayLength=sizeof($arr_approaches);
for ($i=0; $i<$arrayLength; $i++) {
echo $arr_approaches[$i].' - '.$arr_lengths[$i].' | '.$arr_ascents[$i].' | '.$arr_gradients[$i];
echo '<br>';
}
echo '<br>';
unset($arrayLength);
}
$stmt->close();
Specifically should I be creating a class to explode and display the results instead of how I've done it here?
It can be difficult to transition from one coding style that works to another coding style that works unless there is a perceived benefit.
In this example, moving to OOP arbitrarily might only result in different code which does the same thing. So if this is the one and only way you would ever use and output this data, procedural code will provide you with all the directness and specificity you need. Procedural code is good at one-off tasks.
But once you start building classes you begin to think in terms of code re-use and flexibility. e.g. This code mixes the data with the direct HTML output. If it might be handy to have this same data optionally output in CSV, an HTML table or in a collapsible tree view, OOP would be helpful for separating the data result from the output format.