{"flag":true,"single":true,"pageTitle":"Insert Multiple Lines from Text File to MySQL Database Using PHP","post":{"id":47,"user_id":"1","slug":"insert-multiple-lines-from-text-file-to-mysql-database-using-php-mxlv","title":"Insert Multiple Lines from Text File to MySQL Database Using PHP","body":"<p>text.txt<\/p>\r\n<pre class=\"language-markup\"><code>hello line 1\r\nhello line 2\r\nhello line 3<\/code><\/pre>\r\n<p>PHP code<\/p>\r\n<pre class=\"language-markup\"><code>&lt;?php\r\n$servername = \"localhost\";\r\n$username = \"root\";\r\n$password = \"\";\r\n$dbname = \"yourdatabase\";\r\n\r\n$conn = new mysqli($servername, $username, $password, $dbname);\r\nif ($conn-&gt;connect_error) {\r\n  die(\"Connection failed: \" . $conn-&gt;connect_error);\r\n}\r\n\r\n$file = fopen(\"text.txt\", \"r\");\r\nif ($file) {\r\n  $lines = explode(\"\\n\", fread($file, filesize(\"text.txt\")));\r\n  fclose($file);\r\n}\r\nforeach ($lines as $line) {\r\n  $sql = \"INSERT INTO yourtable (yourcolumn) VALUES ('$line')\";\r\n  if ($conn-&gt;query($sql) === TRUE) {\r\n  } else {\r\n    echo \"Error: \" . $sql . \"&lt;br&gt;\" . $conn-&gt;error;\r\n  }\r\n}\r\n$conn-&gt;close();\r\n?&gt;\r\n<\/code><\/pre>","category_id":"1","is_private":"0","created_at":"2023-03-24T09:25:40.000000Z","updated_at":"2023-03-24T09:25:40.000000Z","category":{"id":1,"user_id":"1","name":"PHP","slug":"php-3ius","parent_id":null,"created_at":"2023-03-14T03:58:19.000000Z","updated_at":"2023-03-14T03:58:19.000000Z"},"user":{"id":1,"name":"R GONDAL","email":"rizikmw@gmail.com","email_verified_at":null,"two_factor_confirmed_at":null,"current_team_id":"1","profile_photo_path":null,"created_at":"2023-03-12T10:49:33.000000Z","updated_at":"2025-01-10T12:59:00.000000Z","profile_photo_url":"https:\/\/ui-avatars.com\/api\/?name=R+G&color=7F9CF5&background=EBF4FF"}},"pageDesc":"text.txt hello line 1 hello line 2 hello line 3 PHP code &lt;?php $servername = \"localhost\"; $username = \"root\"; $password = \"\"; $dbname = \" - Insert Multiple Lines from Text File to MySQL Database Using PHP (Updated: March 24, 2023) - Read more about Insert Multiple Lines from Text File to MySQL Database Using PHP at my programming site [SITE]","categories":[]}