What are some strategies for improving the efficiency and readability of PHP code that involves executing SQL queries based on user input from a form?
When executing SQL queries based on user input from a form in PHP, it is important to sanitize and validate the input to prevent SQL injection attacks and errors. One way to improve efficiency and readability is to use prepared statements with placeholders for user input values. This helps separate the SQL query logic from the user input data, making the code more secure and maintainable.
// Assuming $conn is the database connection object
// Sanitize and validate user input
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);
// Prepare the SQL query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();
// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process the results
}
// Close the statement and connection
$stmt->close();
$conn->close();