What are the best practices for using placeholders and wildcards in a SQL query in PHP?

When using placeholders and wildcards in a SQL query in PHP, it is important to properly sanitize user input to prevent SQL injection attacks. Placeholders should be used for dynamic values to ensure safe execution of the query. Wildcards, such as '%' for pattern matching, can be used in conjunction with placeholders to create more flexible queries.

// Example of using placeholders and wildcards in a SQL query in PHP

// Assuming $searchTerm is user input
$searchTerm = $_POST['searchTerm'];

// Sanitize the input
$searchTerm = mysqli_real_escape_string($conn, $searchTerm);

// Prepare the SQL query with a placeholder and wildcard
$sql = "SELECT * FROM users WHERE username LIKE ?";
$stmt = $conn->prepare($sql);
$searchTerm = '%' . $searchTerm . '%';
$stmt->bind_param("s", $searchTerm);
$stmt->execute();
$result = $stmt->get_result();

// Fetch and display results
while ($row = $result->fetch_assoc()) {
    echo $row['username'] . "<br>";
}

$stmt->close();
$conn->close();