How can a PHP beginner create a search function for a MySQL database on a website?

To create a search function for a MySQL database on a website, a PHP beginner can use a form input field to collect user input, then use PHP to query the database based on the search term entered by the user. The PHP code will retrieve matching records from the database and display them on the website.

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

// Check if form is submitted
if(isset($_POST['search'])) {
    $search_term = $_POST['search_term'];

    // Query the database
    $sql = "SELECT * FROM table_name WHERE column_name LIKE '%$search_term%'";
    $result = $conn->query($sql);

    // Display search results
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
        }
    } else {
        echo "No results found";
    }
}

// Close database connection
$conn->close();
?>

<form method="post">
    <input type="text" name="search_term" placeholder="Search...">
    <input type="submit" name="search" value="Search">
</form>