What are the implications of using a variable directly from a text field for database queries in PHP?

Using a variable directly from a text field for database queries in PHP can make your application vulnerable to SQL injection attacks, where an attacker can manipulate the input to execute malicious SQL queries. To prevent this, you should always sanitize and validate user input before using it in database queries. One way to do this is by using prepared statements with parameterized queries, which helps to separate the data from the query execution.

// Assuming $conn is your database connection object

// Retrieve user input from a text field
$userInput = $_POST['user_input'];

// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $userInput);

// Execute the prepared statement
$stmt->execute();

// Fetch the results
$result = $stmt->get_result();

// Process the results as needed
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the statement and connection
$stmt->close();
$conn->close();