How can you securely pass user input from a form to a database query in PHP?
To securely pass user input from a form to a database query in PHP, you should use prepared statements with parameterized queries. This helps to prevent SQL injection attacks by separating the SQL query logic from the user input data.
// Assuming you have established a database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Get user input from a form
$userInput = $_POST['user_input'];
// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $userInput);
// Execute the query
$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();