What are common pitfalls when using PHP to search and display text from a MySQL database?

Common pitfalls when using PHP to search and display text from a MySQL database include not properly sanitizing user input, not handling errors effectively, and inefficient querying methods. To solve these issues, always use prepared statements to prevent SQL injection attacks, implement error handling to gracefully handle any issues that may arise, and optimize your queries to ensure efficient data retrieval.

// Example code snippet using prepared statements and error handling

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare a statement with a placeholder for user input
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE ?");
$searchTerm = "%".$_POST['search']."%";
$stmt->bind_param("s", $searchTerm);

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

// Bind the results to variables
$stmt->bind_result($result1, $result2);

// Fetch and display the results
while ($stmt->fetch()) {
    echo $result1 . " - " . $result2 . "<br>";
}

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