I've written a simple class which should:
- get 10 top cars and 10 top bicycles from database
- write them into 2 different arrays
It works, but I'm trying to find a simpler or clearer solution.
class TopVehicles extends Connection {
private $sql1 = 'SELECT model, price FROM vehicles WHERE type = \'car\' ORDER BY price DESC limit 10';
private $sql2 = 'SELECT model, price FROM vehicles WHERE type = \'bicycle\' ORDER BY price DESC limit 10';
function __construct() {
parent::__construct();
}
public function getTopCars() {
$stmt = $this->mysqli->prepare($this->sql1);
$stmt->execute();
$stmt->store_result();
$row_cnt = $stmt->num_rows;
$stmt->bind_result($model, $price);
while ( $stmt->fetch() ) {
$_result[] =
array(
'Model' => $model,
'Price' => $price
);
}
$stmt->free_result();
$stmt->close();
return $_result;
}
public function getTopBicycles() {
$stmt = $this->mysqli->prepare($this->sql2); /*this is the only line which differs these 2 functions!*/
$stmt->execute();
$stmt->store_result();
$row_cnt = $stmt->num_rows;
$stmt->bind_result($model, $price);
while ( $stmt->fetch() ) {
$_result[] =
array(
'Model' => $model,
'Price' => $price
);
}
$stmt->free_result();
$stmt->close();
return $_result;
}
function __destruct() {
parent::__destruct();
}
}
$obj = new TopProducts();
$_TopCars = $obj->getTopCars();
$_TopVehicles = $obj->getTopBicycles();
It works as expected, but it's messy.
Is it possible to somehow rearrange these 2 methods?
getTopBicycles()
getTopCars()
To stick to the rule: DRY? I've tried to divide them, but I am not able to write proper code. Can you please give me a hint on what I should do?