What best practices should be followed when retrieving data from a database within HTML output in PHP?
When retrieving data from a database within HTML output in PHP, it is important to properly sanitize the data to prevent SQL injection attacks and ensure the security of your application. One common practice is to use prepared statements with parameterized queries to safely retrieve data from the database.
<?php
// Establish a database connection
$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);
}
// Prepare a SQL query
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
// Set parameters and execute
$id = 1;
$stmt->execute();
// Get the result set
$result = $stmt->get_result();
// Fetch data and output in HTML
while ($row = $result->fetch_assoc()) {
echo "<div>{$row['column']}</div>";
}
// Close the statement and connection
$stmt->close();
$conn->close();
?>
Related Questions
- What potential issues can arise when uploading multiple images using PHP and creating thumbnails for each of them?
- What are common pitfalls when trying to submit an array from a form to another page in PHP?
- What are the potential pitfalls of using complex syntax like the one mentioned in the forum thread in PHP development?