How can the PHP script be modified to only write to the database when form fields are filled out?

To only write to the database when form fields are filled out, you can add a condition to check if the form fields are not empty before executing the database write operation. This can be done by using an if statement to validate each form field before inserting the data into the database.

if(!empty($_POST['field1']) && !empty($_POST['field2'])) {
    // Connect to the database
    $conn = new mysqli($servername, $username, $password, $dbname);

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

    // Insert data into the database
    $sql = "INSERT INTO table_name (field1, field2) VALUES ('".$_POST['field1']."', '".$_POST['field2']."')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}