Okay, I've asked in a previous post how best to handle organizing queries. Should I just include in the HTML as needed. This seems wrong, because all I'm getting is a page full of queries littered throughout the HTML.
Or, build functions and call them as needed, etc. Basically, I was told that it kind of depends on the situation and to take it on a case by case basis. Functions being the best solution if they are utilized multiple times.
Below is what I've come up with for a couple of common queries that seem to be popping up throughout my site. The first function contains a query to find out how many of a particular product has been sold. The second function determines the average monthly usage of this product.
Any thought on what I'm doing wrong or how to make it better is appreciated.
<?php
function soldSum($pId) {
$query = "SELECT SUM(orderitems_quantity) AS 'totalSold'
FROM orderitems
WHERE orderitems_productid = '$pId'";
$result = mysql_query($query);
if (!$result) {
error_log(mysql_error()."\n$query");
return false;
}
$totalSold = array();
while($row = mysql_fetch_assoc($result)) {
$totalSold[] = $row['totalSold'];
}
return $totalSold;
}
function monthUsage($create, $sold) {
$diff = (strtotime(date("Y-m-d")) - strtotime($create));
$dayAge = ($diff / 86400) / (30.41666666667);
$productUsage = number_format(($sold / $dayAge), 2);
return $productUsage;
}
?>
I then pop this into a table with other product info to return the results. These functions are being called inside of another query that grabs the other product information.
<?php
foreach(soldSum($products_id) as $key => $option) {
$usage = monthUsage($products_create, $option);
if ($option > '0') {
echo '<td>'.$usage.'</td>';
echo '<td>'.$option.'</td>';
}
else {
echo '<td>0</td>';
echo '<td>0</td>';
}
}
?>