How can a PHP script be modified to display existing database entries when a specific key is entered, and update the entry with new information if it already exists?

To display existing database entries when a specific key is entered and update the entry with new information if it already exists, you can use PHP to query the database for the key entered. If the entry exists, display the existing information. If not, insert a new entry with the key and information provided.

<?php
// Connect to 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 key is entered
if(isset($_POST['key'])) {
    $key = $_POST['key'];
    
    // Query database for key
    $sql = "SELECT * FROM table_name WHERE key = '$key'";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        // Display existing information
        while($row = $result->fetch_assoc()) {
            echo "Existing information: " . $row['column_name'] . "<br>";
        }
    } else {
        // Insert new entry with key and information
        $new_info = "New information";
        $insert_sql = "INSERT INTO table_name (key, column_name) VALUES ('$key', '$new_info')";
        if ($conn->query($insert_sql) === TRUE) {
            echo "New entry added successfully";
        } else {
            echo "Error: " . $insert_sql . "<br>" . $conn->error;
        }
    }
}

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