I want to make a list of Best selling prints in my store. I have a table (print_for_sale) which has fk_sale_id and fk_print_id where I can see how many prints have been bought.
I came up with this code to print out an organized list, from most bought to least (not sure it is entirely correct):
<?php
$sql = "SELECT fk_print_id as printId, COUNT(print_for_sale_id) as saleCount
FROM print_for_sale
GROUP BY fk_print_id
ORDER BY saleCount DESC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['printId']; echo $row['saleCount']; }
?>
I'm trying to make a transition of this to my model, controller and view (mvc) but I'm having a lot of trouble. I'm new to this and I've tried in so many different ways, none of which seem to work. I'm lost. Right now I have it like this (and it prints out nothing) or the only thing it prints out is "Notice undefined variable arr" when I make an echo in my view
model.php
function getBestSelling() {
$sql = "SELECT fk_print_id as printId, COUNT(print_for_sale_id) as saleCount
FROM print_for_sale
GROUP BY fk_print_id
ORDER BY saleCount DESC";
$result = $this->conn->query($sql);
return $this->buildArr($result);
}
controller.php
function bestselling() {
$arr = $this->model->getBestSelling();
print_r($arr);
include 'view.php';
}
view.php
<?php echo $arr['printId'] ?>
I want to print out the result of the query but nothing is working. I'm sorry if this isn't an appropriate question but I could really use some help understanding this.
I'm not using any framework.
In my model I do have a class model { }
, a function __construct()
and a function __destruct()
. I also have a function to build the arrays.
function buildArr($result) {
$arr = array();
while ($row = $result->fetch_assoc()) {
array_push($arr, $row);
}
return $arr;
}
In my controller I include 'model.php';
and have a class Controller {}
and function __construct() { $this->model = new model();}
.
I also have a index.php where I start the session and define("BASE_URL", 'http://' . $_SERVER['SERVER_NAME'] . '/printstore/index.php/');
The app is working. I can already register users, login and make purchases. I just can't seem to get this part of the code right. Would appreciate some help! Sorry for the long post and thank you in advance.