What best practices should be followed when handling database connections and queries in PHP to ensure successful data insertion?

When handling database connections and queries in PHP to ensure successful data insertion, it is important to properly sanitize user input to prevent SQL injection attacks, use prepared statements to prevent SQL injection and improve performance, and handle errors gracefully to provide meaningful feedback to users.

// Establish database connection
$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 and bind SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Sanitize user input
$value1 = mysqli_real_escape_string($conn, $_POST['value1']);
$value2 = mysqli_real_escape_string($conn, $_POST['value2']);

// Execute the statement
$stmt->execute();

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