What are some best practices for establishing a connection and transferring data to a SQL database using PHP?

Establishing a connection and transferring data to a SQL database using PHP involves creating a connection to the database server, selecting the appropriate database, and executing SQL queries to insert or retrieve data. It is important to handle errors gracefully and securely by using prepared statements to prevent SQL injection attacks.

<?php
// Database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

// Example query to insert data into a table
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";

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

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