What are the best practices for importing data into a database using PHP?

When importing data into a database using PHP, it is important to sanitize the input to prevent SQL injection attacks. It is also recommended to use prepared statements to securely execute SQL queries. Additionally, error handling should be implemented to catch any issues during the import process.

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

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

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

// Sanitize input data
$data = mysqli_real_escape_string($conn, $data);

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

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

$stmt->execute();

// Check for errors during query execution
if ($stmt->error) {
    echo "Error: " . $stmt->error;
}

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