What are some best practices for parsing and storing data from text files into a MySQL database using PHP?

When parsing and storing data from text files into a MySQL database using PHP, it is important to properly handle the file reading, data parsing, and database insertion processes. One best practice is to read the text file line by line, parse the data into appropriate fields, and then insert the data into the database using prepared statements to prevent SQL injection attacks.

<?php
// Open the text file for reading
$file = fopen('data.txt', 'r');

// Connect to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Read the file line by line and insert data into the database
while (!feof($file)) {
    $line = fgets($file);
    $data = explode(',', $line); // Assuming data is comma-separated

    // Prepare and bind the insert statement
    $stmt = $mysqli->prepare("INSERT INTO table_name (field1, field2, field3) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $data[0], $data[1], $data[2]);
    $stmt->execute();
}

// Close the file and database connection
fclose($file);
$stmt->close();
$mysqli->close();
?>