How can conditional statements in PHP be optimized to prevent unwanted SQL queries from executing based on user input?

To prevent unwanted SQL queries from executing based on user input, you can optimize conditional statements in PHP by validating and sanitizing user input before constructing and executing SQL queries. This can help prevent SQL injection attacks and ensure that only safe and valid input is used to query the database.

// Validate and sanitize user input
$user_input = $_POST['user_input'];
$filtered_input = filter_var($user_input, FILTER_SANITIZE_STRING);

// Check if the input is valid before executing SQL query
if (!empty($filtered_input)) {
    // Construct and execute SQL query using the sanitized input
    $sql = "SELECT * FROM table WHERE column = '$filtered_input'";
    $result = mysqli_query($connection, $sql);
    
    // Process the query result
    if ($result) {
        // Code to handle query result
    } else {
        echo "Error executing SQL query";
    }
} else {
    echo "Invalid input";
}