Hussain ALmadhoon Hussain ALmadhoon - 6 months ago 14
PHP Question

php sort sql data

i have sql database contain books detail and i have drop down menu to select book category to list all books in this category. then i have link to sort the books by the price i try this but not work

<a href="view.php?sort=priceASD">order by price Low to high</a>
if( $_GET['sort'] =='priceASD')
{
$x=$db->query("SELECT * FROM books WHERE category='Children' AND ORDER BY price ASC");
foreach($x as $row)
echo "<tr><td><a href='displayinfo.php?booksid=".$row['id']."'>".$row['title']."</a></td><td><a href='displayinfo.php?booksid=".$row['id']."'><img src=".$row['picture']." height='100' width='100'></a></td><td>$".$row['price']."</td></tr>";
}


and this to display the books by category:

if($value == 'Children')
{
$r=$db->query("SELECT * FROM books WHERE category='Children'");
echo "<table>";
foreach($r as $row)
echo "<tr><td><a href='displayinfo.php?booksid=".$row['id']."'>".$row['title']."</a></td><td><a href='displayinfo.php?booksid=".$row['id']."'><img src=".$row['picture']." height='100' width='100'></a></td><td>$".$row['price']."</td></tr>";

echo "</table>";
}

Answer

'AND' or 'OR' keywords used in SQL for use more then one conditions. 'AND' is not working with 'ORDER BY' keyword. By default 'ORDER BY' sort data in ascending order. So, no need to use ASC.

 SELECT * FROM books WHERE category='Children' ORDER BY price

Hope this code will work for you.