What best practices should be followed when retrieving and displaying data from a MySQL database in a PHP script to ensure proper sorting and display order?
When retrieving and displaying data from a MySQL database in a PHP script, it is important to use the ORDER BY clause in your SQL query to ensure proper sorting of the data. Additionally, you should sanitize user input to prevent SQL injection attacks and properly escape any output to prevent cross-site scripting vulnerabilities. Finally, consider using pagination to limit the number of records displayed on each page for better performance.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Retrieve data from database with ORDER BY clause
$query = "SELECT * FROM table_name ORDER BY column_name";
$result = mysqli_query($connection, $query);
// Loop through results and display data
while ($row = mysqli_fetch_assoc($result)) {
// Sanitize and escape output before displaying
$data = htmlspecialchars($row['column_name']);
echo "<p>$data</p>";
}
// Close database connection
mysqli_close($connection);