I have A data in txt file I want to save it in database
mytxtfile
xxxxxxxxx
xxxxxxxxx
xxxxxxxxx
I want to Save each line in database...
I want to make a PHP file which take 1st line from txt file and save it in db. Then again second line and so on....
myphpcode
$myFile = "data.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (ID)
VALUES (''.$theData.'')");
mysqli_close($con);
?>
This Code Is Just Saving 1st line..
You should try something like:
while (!feof($fh)) {
$line = fgets($fh);
mysqli_query($con,"INSERT INTO Persons (ID)
VALUES ('".$line."')");
}
The loop goes through each line of the file and then inserts it into the database.
It is not the most efficient way, especially if you have a very large number of lines, but it does the trick. If you do have very many lines, than you should try and do everything in a single INSERT.
it's as simple as:
$ip = fopen('data.txt', "r");
$line = trim(fgets($ip));
while(!feof($ip)){
// do something with line in $line
//....
// reading next line
$line = trim(fgets($ip));
}
Two possibilities for this question:
First one just parse file using the SplFileObject http://php.net/manual/fr/class.splfileobject.php
In my mind using Spl object is always a good way of coding in PHP.
The second one consist in using LOAD DATA INFILE functionality of MySQL http://dev.mysql.com/doc/refman/5.6/en/load-data.html
This is a good way if you don't need to use data from the file but just storing them.
I'll answer your question first. Your code is fine in it's present condition but the problem is only one line being read. If you want to read the complete file content, you'll have to loop through each line. Change your code to include a while loop, like so:
$fh = fopen('file.txt', 'r');
while(!feof($fh)){
$theData = fgets($fh);
echo $theData; //save it to DB
}
feof()
checks for end-of-file on a file pointer. If EOF (end of file) is reached, it'll exit the loop.
Alternative solution:
Using LOAD DATA INFILE
:
Example:
LOAD DATA INFILE 'data.txt' INTO TABLE Persons
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '
'
IGNORE 1 LINES;
The advantage of using LOAD DATA INFILE
is that it's considerably faster than other methods, but the speed may vary depending on other factors.