What are the best practices for automatically writing data to a database using PHP without user intervention?

When automatically writing data to a database using PHP without user intervention, it is important to ensure that the data is sanitized to prevent SQL injection attacks. Additionally, using prepared statements can help improve performance and security by separating SQL logic from data input.

<?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);
}

// Prepare SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Set values and execute statement
$value1 = "value1";
$value2 = "value2";
$stmt->execute();

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