How to insert .txt file data into database using php?

by ryan.murray , in category: PHP General , 5 months ago

How to insert .txt file data into database using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 5 months ago


To insert the data from a .txt file into a database using PHP, you can follow these steps:

  1. Establish a connection to the database using PHP's MySQLi or PDO extension. Here is an example using MySQLi: $servername = "localhost"; $username = "your_username"; $password = "your_password"; $database = "your_database"; // Create a new MySQLi instance $conn = new mysqli($servername, $username, $password, $database); // Check the connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
  2. Open the .txt file and read its contents using file_get_contents() or fopen(). $filepath = "path/to/your/file.txt"; $contents = file_get_contents($filepath); // or $file = fopen($filepath, "r"); $contents = fread($file, filesize($filepath));
  3. Process the contents of the .txt file and split them into individual records (assuming each line represents one record). You can use the explode() function to split the contents by a delimiter, such as a new line (" ") or tab (" "). $records = explode(" ", $contents);
  4. Loop through the records and insert them into the database using SQL INSERT statements. foreach ($records as $record) { // Assuming the data in the .txt file is tab-separated with columns "column1" and "column2" $columns = explode(" ", $record); $column1 = $conn->real_escape_string($columns[0]); $column2 = $conn->real_escape_string($columns[1]); // Create and execute the SQL INSERT statement $sql = "INSERT INTO your_table (column1, column2) VALUES ('$column1', '$column2')"; if ($conn->query($sql) === TRUE) { echo "Record inserted successfully."; } else { echo "Error: " . $sql . "" . $conn->error; } }
  5. Close the file and the database connection. fclose($file); $conn->close();

Make sure your database table structure matches the data in the .txt file, and update the variable names, database configurations, and table names as per your needs.