How to use GROUP BY + ORDER BY + WHERE together with GET in PHP?

77
April 13, 2019, at 2:10 PM

I try to make a sales report document using php and connect it from mysql database.
How can I use where + group by + order (mysql query) with PHP get method?
I could just use SELECT and WHERE, but how to add GROUP BY and ORDER BY query?

$date=$_GET['date'];
$query=mysql_query("select * from product_sold where date=" . $date);
while($lihat=mysql_fetch_array($query)){
    $pdf->Cell(1, 0.8, $no , 1, 0, 'C');
    $pdf->Cell(3, 0.8, $lihat['date'],1, 0, 'C');
    $pdf->Cell(6, 0.8, $lihat['product'],1, 0, 'C');
    $pdf->Cell(3, 0.8, $lihat['quantity'], 1, 0,'C');
    $pdf->Cell(4, 0.8, "Rp. ".number_format($lihat['price'])." ,-", 1, 0,'C');
Answer 1

You use GROUP BY and ORDER BY at the end of your sql statements like this...

"SELECT * FROM table WHERE date = $date ORDER BY desiredCategory "

Also, you REALLY need to be using prepared statements. You are WIDE OPEN to sql injection attacks the way you're doing this.

More about GROUP BY
More about ORDER BY
More about prepared statements

Answer 2

You can add the GROUP BY after you WHERE filters, then you can add the ORDER BY.

SELECT *
FROM product_sold
WHERE date = '$date'
GROUP BY id
ORDER BY product ASC

And be aware from sql injection like @jtylerm said.

READ ALSO
R and RMySQL cant write table to MySQL database

R and RMySQL cant write table to MySQL database

I am trying to write my table from R to the MySQL database

70
Need help to optimze code , cant decide to use dataframe for sorting or mysql

Need help to optimze code , cant decide to use dataframe for sorting or mysql

I am writing code to get data from 1m database (size can increase)I have mysql server locally and writing everything in python

56
Is a good practice to use handler with thread inside presenter to retrieve data?

Is a good practice to use handler with thread inside presenter to retrieve data?

I'm starting with android and I whould like make using the best practices

40