Developer Snippet Diary

Insert Multiple Lines from Text File to MySQL Database Using PHP

text.txt

hello line 1
hello line 2
hello line 3

PHP code

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "yourdatabase";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$file = fopen("text.txt", "r");
if ($file) {
  $lines = explode("\n", fread($file, filesize("text.txt")));
  fclose($file);
}
foreach ($lines as $line) {
  $sql = "INSERT INTO yourtable (yourcolumn) VALUES ('$line')";
  if ($conn->query($sql) === TRUE) {
  } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
  }
}
$conn->close();
?>
Posted by: R GONDAL
Email: rizikmw@gmail.com