I know this has been asked before -- I tried to read previous Q&A on the topic but I'm still stuck. Probably I read too many Q&A and have a bad mix of techniques as a result.
I don't get an error, I just don't get anything in my table. The echo $i is to help debug and I only ever get a 0 rather than expected 0 1 2 3 ... N rows.
My DB connection credentials are all fine I use them all over my site for Select statements.
$csv_file = str_getcsv("https://ds.data.jma.go.jp/tcc/tcc/products/gwp/temp/list/csv/year_wld.csv");
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile))
{
echo $i;
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$yrr = $csv_array[0];
$vals= $csv_array[1];
$sql1 = "INSERT INTO Table1(Year,Value) VALUES(" . $yrr . "," . $vals. ")";
$conn->query($sql1);
$i++;
}
The main problem here is the fact that you are trying to open a text variable as a file:
$csvfile = fopen($csv_file, 'r');
In fact you already have an array from from str_getcsv so your whole code should look like (if you can read the whole file at once):
$csvFile = array_map('str_getcsv', file("https://ds.data.jma.go.jp/tcc/tcc/products/gwp/temp/list/csv/year_wld.csv"));
array_shift($csvFile); //we remove the headers
$i = 0;
/**
* Removes all the "*" and "+" symbols as I assume that you want a float since you are not wrapping it in the sql query
*/
function removeUnwantedChars($string) {
return preg_replace('/[^0-9\\.\\-]/i', '', $string);
}
foreach($csvFile as $csvData) {
echo $i++;
$yrr = $csvData[0];
$vals = removeUnwantedChars($csvData[1]);
$sql1 = "INSERT INTO Table1(Year,Value) VALUES(" . $yrr . "," . $vals. ")";
$conn->query($sql1);
}
If you cannot read it all at once then I suggest to first download the file line by line:
<?php
$url = "https://ds.data.jma.go.jp/tcc/tcc/products/gwp/temp/list/csv/year_wld.csv";
$fileHandle = fopen($url, "r");
/**
* Removes all the "*" and "+" symbols
*/
function removeUnwantedChars($string) {
return preg_replace('/[^0-9\\.\\-]/i', '', $string);
}
$i = 0;
$headersSkipped = false;
while ($csvData = fgetcsv($fileHandle)) {
if (!$headersSkipped) {
$headersSkipped = true;
continue;
}
echo $i++;
$yrr = $csvData[0];
$vals = removeUnwantedChars($csvData[1]);
$sql1 = "INSERT INTO Table1(Year,Value) VALUES(" . $yrr . "," . $vals. ")";
$conn->query($sql1);
}
fclose($fileHandle);
Yet like said by #Shadow above it is always great to be more verbose. So in case query returned false then it would be great to output the last error (if you are using PDO then errorInfo() function.
Related
I have a file that has long string; what i could not do is search and count
a particular subsequence. I want to count the number of "ABD" substring in veryLongWord.txt file. The below is what i have currently.
<?php
$file = fopen("veryLongWord.txt", "r");
/*
inside veryLongWord.txt
ABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABD
ABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABD
*/
$word = "";
while(!feof($file)) {
$line = fgets($file);
$word .= trim($line);
}
fclose($file);
$subseq = null;
$count = 0;
print $subseq . " shows " . $count . " times <br/>";
?>
There's already a function to do that: substr_count
$contentsOfVeryLongWord = file_get_contents("veryLongWord.txt");
$count = substr_count($contentsOfVeryLongWord, 'ABD');
I got this code that will :
Ask user to upload .docx which contains format like this (erina, natasha culler, danial joshstone)
After they upload the list name will be inserted to the database. Every name got teir own row in database.
The code below is running well. But after the name is inserted, the database becomes like this:
If you see the first name erina, you can see that it got a big space. But rest of the names were inserted perfectly. It's just for the first one. I dont know why. Because of that space I cant search query the erina name. I tried many things, but still got that result.
<?php
include 'configure.php';
if(isset($_FILES['uploaded_file']))
{
$document_path = $_FILES ['uploaded_file']['tmp_name'];
$document_name=$_FILES ['uploaded_file']['name'];
function extracttext($filename,$filepath)
{
$ext = explode('.', $filename);
$ext=end ($ext);
if($ext == 'docx')
$dataFile = "word/document.xml";
else
$dataFile = "content.xml";
$zip = new ZipArchive;
if (true === $zip->open($filepath))
{
if (($index = $zip->locateName($dataFile)) !== false)
{
$text = $zip->getFromIndex($index);
$xml = new DOMDocument;
$xml->loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
return strip_tags($xml->saveXML());
}
$zip->close();
}
return "File not found";
}
$friendslist = extracttext($document_name,$document_path);
$id = "24";
$friendarray = explode(",", $friendslist);
$frienduserarray = array();
for ($n = 0; $n < count($friendarray); $n++)
{
$friendidpush = "('".$id."','".$friendarray[$n]."'),";
array_push($frienduserarray, $friendidpush);
}
$query = "INSERT INTO keywords (criteria, value) VALUES ";
$friendarray = explode(",", $friendslist);
foreach ($friendarray as $friend)
{
$query .= "('" . $id . "','" . $friend . "'),";
}
$query = substr($query, 0, -1); // remove trailing comma
mysql_query($query);
}
?>
How to fix this problem?
Alternatively, If you want to remove to much spacing on each exploded value, you could use array_map then trim. Consider this example:
// this is just a sample!
$friendarray = 'friend1, friend2, friend3, friend4';
$friendarray = explode(',', $friendarray);
$friendarray = array_map('trim', $friendarray);
echo "<pre>";
var_dump($friendarray);
echo "</pre>";
Using trim() will help to remove whitespace in each word.
$query .= "('" . $id . "','" . trim($friend) . "'),";
You can refer to the documentation of trim() function here, for further functionality of the same.
Use trim() to remove whitespace before inserting
foreach ($friendarray as $friend)
{
$query .= "('" . $id . "','" . trim($friend) . "'),";
}
i want to insert data from a csv file into my mysql database with php. But i dont know what i doing wrong.
This is my php code
if ($_FILES[csv][size] > 0){
$csv_file = $_FILES[csv][tmp_name]; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['id'] = $csv_array[0];
$insert_csv['name'] = $csv_array[1];
$insert_csv['email'] = $csv_array[2];
if(!empty($insert_csv['email'])){
$query = "INSERT INTO contacts(id,name,email)
VALUES('','".$insert_csv['name']."','".$insert_csv['email']."')";
$n=mysqli_query($database->connection,$query);
}
$i++;
}
fclose($csvfile);
}
This is my csv looks like.
id---- name ------- email
1 ---- user1--------bla#hotmail.com
2 ---- user2 --------blah
3------ user 3 ------ blah
When i run this code my mysql results are
in email table = ##0.00 "TL")$# en in my name table= also ##0.00
"TL")$#;
What do i wrong?
You might want to use MySQL to do the whole loading process with the LOAD DATA INFILE statement.
if($_FILES['csv']['error'] === UPLOAD_ERR_OK && $_FILES['csv']['size'] > 0) {
$query = "LOAD DATA INFILE '" . $_FILES['csv']['tmp_name']
. "' INTO TABLE contacts FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' (id, name, email);";
if(!mysqli_query($query)){
die('Oops! Something went wrong!');
}
}
If required you can tweak the loading parameters (FIELDS TERMINATED BY, ENCLOSED BY, LINES TERMINATED BY).
Do take note that if you use this approach your temporary file needs to be stored in a place where its accessible by the MySQL server (like /tmp).
To start with, I think you should remove the first
$data = fgetcsv($getfile, 1000, ",");
line, outside of the while loop...
Please try like this as a example , it should work for you as you want
I think you missed qoutes in "
$query = "INSERT INTO contacts(id,name,email)
VALUES('".$col1."','".$col2."','".$col3."')";
"
<?php
$csv_file = 'C:\wamp\www\stockmarket\test.csv'; // Name of your CSV file with path
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
// SQL Query to insert data into DataBase
$query = "INSERT INTO contacts(id,name,email)
VALUES('".$col1."','".$col2."','".$col3."')";
$s=mysql_query($query, $connect );
}
}
}
?>
I have the PHP code as below:
<?php
$path = "files/stats_pmta.affinitead.net.2012-12-12.txt";
$num = 10;
$fh = #fopen($path, 'r');
if ($fh){
for ($i=0;$i<$num;$i++){
$newfile = fgets($fh,1024);
$t = explode(";", $newfile);
echo $t;
echo "<br>";
}
} else {
echo 1;
}
?>
I want to read all data in file stats_pmta.affinitead.net.2012-12-12.txt that read only first 10 lines of the file below:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
2012-12-12-0551;affinitead.net;1221588;106346;8.70;wanadoo.fr;123562;9227;7.46
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.fr;104819;1685;1.60
2012-12-12-0551;affinitead.net;1221588;106346;8.70;orange.fr;87132;7341;8.42
2012-12-12-0551;affinitead.net;1221588;106346;8.70;laposte.net;79597;1040;1.30
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.fr;77601;14107;18.17
2012-12-12-0551;affinitead.net;1221588;106346;8.70;neuf.fr;67392;1793;2.66
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.com;55300;10494;18.97
2012-12-12-0551;affinitead.net;1221588;106346;8.70;free.fr;43422;1706;3.92
2012-12-12-0551;affinitead.net;1221588;106346;8.70;sfr.fr;39063;251;.64
2012-12-12-0551;affinitead.net;1221588;106346;8.70;aol.com;32061;9859;30.75
2012-12-12-0551;affinitead.net;1221588;106346;8.70;club-internet.fr;22424;233;1.03
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.com;18646;1365;7.32
2012-12-12-0551;affinitead.net;1221588;106346;8.70;voila.fr;18513;3650
After I read first top 10 lines I want to display the word in each line like:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
I want to display gmail.com 123577 7780 6.29
But PHP code above I just got the output array.I don't know how to fix this.Anyone help me please , Thanks.
You could do something like this:
$path = 'path/to/file'
$fp = fopen($path, 'r');
$count = 0;
while($columns = fgetcsv($fp, 256, ';', '"')
{
if(++$count > 10)
break;
echo implode("\t", $colums);
}
If you don't know, how implode works, look here: http://de1.php.net/manual/de/function.implode.php
This is a way you could do it by using the PHP-function explode.
$textFile = file_get_contents("test.txt");
$lineFromText = explode("\n", $textFile);
$row = 0;
foreach($lineFromText as $line)
{
if($row <= 10)
{
$words = explode(";",$line);
echo $words[5] . ' ' . $words[6] . ' ' . $words[7] . ' ' . $words[8];
$row++;
}
}
Edited the code so that you can replace your own, you might want to check if the file is empty e t c before trying to do anyting thou.
I have this large (and oddly formatted txt file) from the USDA's website. It is the NUT_DATA.txt file.
But the problem is that it is almost 27mb! I was successful in importing the a few other smaller files, but my method was using file_get_contents which it makes sense why an error would be thrown if I try to snag 27+ mb of RAM.
So how can I import this massive file to my MySQL DB without running into a timeout and RAM issue? I've tried just getting one line at a time from the file, but this ran into timeout issue.
Using PHP 5.2.0.
Here is the old script (the fields in the DB are just numbers because I could not figure out what number represented what nutrient, I found this data very poorly document. Sorry about the ugliness of the code):
<?
$file = "NUT_DATA.txt";
$data = split("\n", file_get_contents($file)); // split each line
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database", $link);
for($i = 0, $e = sizeof($data); $i < $e; $i++)
{
$sql = "INSERT INTO `USDA` (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17) VALUES(";
$row = split("\^", trim($data[$i])); // split each line by carrot
for ($j = 0, $k = sizeof($row); $j < $k; $j++) {
$val = trim($row[$j], '~');
$val = (empty($val)) ? 0 : $val;
$sql .= ((empty($val)) ? 0 : $val) . ','; // this gets rid of those tildas and replaces empty strings with 0s
}
$sql = rtrim($sql, ',') . ");";
mysql_query($sql) or die(mysql_error()); // query the db
}
echo "Finished inserting data into database.\n";
mysql_close($link);
?>
If you have to use PHP, you can read the file line by line using fopen and fgets
<?
$file = "NUT_DATA.txt";
$fh = #fopen( $file, "r" ); // open the file for reading
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database", $link);
while( !feof( $fh ) )
{
$data = fgets( $fh, 4096 ); // read line from file
$sql = "INSERT INTO `USDA` (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17) VALUES(";
$row = split("\^", trim($data)); // split each line by carrot
for ($j = 0, $k = sizeof($row); $j < $k; $j++) {
$val = trim($row[$j], '~');
$val = (empty($val)) ? 0 : $val;
$sql .= ((empty($val)) ? 0 : $val) . ','; // this gets rid of those tildas and replaces empty strings with 0s
}
$sql = rtrim($sql, ',') . ");";
mysql_query($sql) or die(mysql_error()); // query the db
}
echo "Finished inserting data into database.\n";
fclose( $fh );
mysql_close($link);
?>
Check out the fgets documentation for more info
Read the file line by line so that you're not loading the entire file in memory. Use
set_time_limit(0);
To avoid having your script time out.
http://php.net/manual/en/function.set-time-limit.php
You can increase the amount of memory each script can use by setting this value in php.ini:
memory_limit = 64M
Having said this: do you have to use PHP? other scripting languages (like python) might be more appropriate for this kind of tasks.