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

Member

by ryleigh , in category: PHP General , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 6 months ago

@ryleigh 

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

  1. Read the contents of the .txt file using PHP. You can do this using the file_get_contents() function or by opening the file using fopen() and reading the contents line by line.
  2. Parse the data from the .txt file and structure it in a format that can be inserted into the database. This could involve splitting the data into different fields or columns, depending on the structure of your database table.
  3. Establish a connection to your database using PHP. You can use the mysqli or PDO extension to connect to the database and perform SQL queries.
  4. Use SQL queries to insert the parsed data from the .txt file into the database. You can use the INSERT INTO statement to insert the data into the appropriate table.


Here's an example code snippet to demonstrate how to insert data from a .txt file into a database:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
// Read the contents of the .txt file
$data = file_get_contents('data.txt');

// Parse the data and prepare it for insertion into the database
$lines = explode("
", $data);
foreach ($lines as $line) {
    $fields = explode(",", $line); // Assuming data is comma-separated
    $field1 = $fields[0];
    $field2 = $fields[1];
    
    // Connect to the database
    $conn = new mysqli('localhost', 'username', 'password', 'database_name');

    // Insert the data into the database
    $sql = "INSERT INTO table_name (field1, field2) VALUES ('$field1', '$field2')";
    if ($conn->query($sql) === TRUE) {
        echo "Data inserted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}
?>


Note: Ensure that you replace the placeholders (e.g., 'localhost', 'username', 'password', 'database_name', 'table_name') with the actual values that correspond to your database configuration and table structure.