What best practices should be followed when structuring a PHP script that handles user authentication and database queries for a search feature?

When structuring a PHP script that handles user authentication and database queries for a search feature, it is important to follow best practices to ensure security and efficiency. This includes using prepared statements to prevent SQL injection attacks, validating user input to prevent malicious code execution, and implementing proper error handling to provide feedback to users.

<?php
// Connect to the 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);
}

// User authentication
$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // User authenticated
} else {
    // Invalid credentials
}

// Search feature
$search_term = $_GET['search'];

$stmt = $conn->prepare("SELECT * FROM products WHERE name LIKE ?");
$search_term = "%$search_term%";
$stmt->bind_param("s", $search_term);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Display search results
}

$conn->close();
?>