What are some best practices for displaying data from a MySQL database in a PHP application?
When displaying data from a MySQL database in a PHP application, it is important to follow best practices to ensure security, efficiency, and readability. One common approach is to use prepared statements to prevent SQL injection attacks and properly escape any user input. Additionally, consider using pagination to display large datasets in a more manageable way and optimize your queries to only retrieve the necessary data.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve data from database using prepared statement
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
// Display data in a table
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['name'] . "</td><td>" . $row['email'] . "</td></tr>";
}
echo "</table>";
// Close connection
$stmt->close();
$conn->close();