What best practices should be followed when retrieving and displaying data from a MySQL database using PHP?
When retrieving and displaying data from a MySQL database using PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize user input and validate data before querying the database. Finally, handle errors gracefully and securely display data to users.
// 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 and display data from database using prepared statement
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1; // Example ID
$stmt->execute();
$stmt->bind_result($id, $name, $email);
while ($stmt->fetch()) {
echo "ID: " . $id . " | Name: " . $name . " | Email: " . $email . "<br>";
}
$stmt->close();
$conn->close();
Keywords
Related Questions
- What are the potential pitfalls of not using error_reporting and display_errors settings in PHP scripts?
- What are the key considerations when integrating a login script on a website with a phpBB forum?
- How can PHP developers utilize IDEs or debugging tools to enhance their workflow and troubleshoot code effectively, as suggested by forum members?