What best practices should be followed when constructing conditional SQL queries in PHP to avoid unintentional data retrieval?

When constructing conditional SQL queries in PHP, it is important to sanitize and validate user input to prevent SQL injection attacks and unintentional data retrieval. One way to achieve this is by using prepared statements with parameter binding, which separates the SQL query logic from the user input values.

// Assuming $conn is your database connection

// Sanitize and validate user input
$userInput = $_POST['user_input'];
if (!is_numeric($userInput)) {
    // Handle invalid input error
}

// Prepare the SQL query with a placeholder for the user input
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name = ?");
$stmt->bind_param("s", $userInput);

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

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

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

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