How can the PHP code be modified to properly handle and display data from a database without risking code execution vulnerabilities?
To properly handle and display data from a database without risking code execution vulnerabilities, you should use prepared statements with parameterized queries to prevent SQL injection attacks. This approach ensures that user input is properly sanitized before being used in database queries, reducing the risk of malicious code execution.
// Connect to the 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);
}
// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
// Set the parameter value and execute the query
$id = 1;
$stmt->execute();
// Get the result set
$result = $stmt->get_result();
// Display the data
while($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
echo "Email: " . $row['email'] . "<br>";
}
// Close the statement and connection
$stmt->close();
$conn->close();