What best practice should be followed when incorporating user input into a MySQL query in PHP?
When incorporating user input into a MySQL query in PHP, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate the SQL query from the user input, ensuring that malicious code cannot be injected into the query. This helps protect the database from unauthorized access and manipulation.
// 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 statement with a placeholder for user input
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
// Bind the user input to the placeholder
$username = $_POST['username'];
$stmt->bind_param("s", $username);
// Execute the prepared statement
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$conn->close();