What best practices should be followed when configuring MySQL data in PHP scripts to ensure proper connection and data insertion?

When configuring MySQL data in PHP scripts, it is important to follow best practices to ensure proper connection and data insertion. This includes securely storing database credentials, using prepared statements to prevent SQL injection attacks, and properly handling errors to troubleshoot any issues that may arise.

<?php
// Securely store database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

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

// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

$value1 = "value1";
$value2 = "value2";

$stmt->execute();

echo "New record inserted successfully";

$stmt->close();
$conn->close();
?>