What is the potential issue with the SELECT query in the provided PHP code?
The potential issue with the SELECT query in the provided PHP code is that it is vulnerable to SQL injection attacks. To prevent this, you should use prepared statements with parameterized queries. This will sanitize user input and prevent malicious SQL code from being executed.
// Fix for the SELECT query using prepared statements
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Prepare and bind the SELECT query
$stmt = $connection->prepare("SELECT id, name FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();
// Bind result variables
$stmt->bind_result($id, $name);
// Fetch results
while ($stmt->fetch()) {
echo "ID: " . $id . " Name: " . $name . "<br>";
}
$stmt->close();
$connection->close();