How can PHP be used to sort data retrieved from a MySQL database in an online shop script?
To sort data retrieved from a MySQL database in an online shop script using PHP, you can use the ORDER BY clause in your SQL query. This allows you to specify the column by which you want to sort the data, as well as the sorting order (ASC for ascending or DESC for descending). By dynamically generating the ORDER BY clause based on user input or predefined criteria, you can display the data in the desired order on your online shop.
// Connect to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Define the sorting criteria
$sort_column = "price"; // Example sorting by price
$sort_order = "ASC"; // Sorting order - ASC or DESC
// Retrieve data from the database and sort it
$query = "SELECT * FROM products ORDER BY $sort_column $sort_order";
$result = mysqli_query($connection, $query);
// Display the sorted data
while ($row = mysqli_fetch_assoc($result)) {
echo $row['product_name'] . " - Price: $" . $row['price'] . "<br>";
}
// Close the database connection
mysqli_close($connection);
Related questions
-
PID multiple servers identification
-
while loop PHP code unexpected errors
-
GDPR compliance data protection regulations tracking scripts