I don't know how i can use this code below in Laravel 5.8 I already tried but i doesn't work correctly.
$sql = mysqli_query($db, "SELECT *, SUM(amount) AS SumBudget FROM messages GROUP BY contact_phone ORDER BY SUM(amount) DESC LIMIT 3");
$orderList = 0;
while ($data = mysqli_fetch_assoc($sql))
{
$orderList++;
$user = $data['user'];
$cost = $data['SumBudget'];
if ($orderList == 1) {
printf("%d. %s %d฿<br>", $orderList, $user, $cost);
}
else if ($orderList == 2)
{
printf("%d. %s %d฿<br>", $orderList, $user, $cost);
}
else
{
printf("%d. %s %d฿<br>", $orderList, $user, $cost);
}
}
My code already tried.
$data = DB::table('messages')
->where('phone_number', $request->phone_number)
->select(DB::raw('SUM(amount) as cost'))
->groupBy(DB::raw('contact_phone'))
->orderBy(DB::raw('SUM(amount)', 'DESC'))
->limit(3)
->get();
Can anyone help me, Thank you.
DB::connection()->getPdo()->query(...)should be fine you don't have user input in your qeury.. Atleast not in the example at the top..SELECT * GROUP BY contact_phoneis generally not how you should be writing SQL.. MySQL Handling of GROUP BY .