What are best practices for using PHP to search for specific criteria in a MySQL database?

When searching for specific criteria in a MySQL database using PHP, it is best practice to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize user input to ensure data integrity and security. Finally, using proper error handling techniques can help troubleshoot any issues that may arise during the search process.

// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Prepare a SQL statement with placeholders for user input
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name = ?");

// Bind the user input to the placeholders
$search_criteria = $_POST['search_criteria'];
$stmt->bind_param("s", $search_criteria);

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

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

// Display the results
while ($row = $result->fetch_assoc()) {
    echo "ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
}

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