What are the potential consequences of not properly validating user input in a PHP SQL query?

If user input is not properly validated in a PHP SQL query, it can lead to SQL injection attacks where malicious users can manipulate the query to execute unauthorized commands on the database. To prevent this, always sanitize and validate user input before using it in SQL queries by using prepared statements or parameterized queries.

// Example of using prepared statements to validate user input in a PHP SQL query

// Assume $conn is the database connection object

// User input
$user_input = $_POST['user_input'];

// Prepare a SQL statement with a placeholder for the user input
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);

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

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

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

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