I am facing this problem some past days and now frustrate because I have to do it.
I need to update my CSV file columns name with database table header. My database table fields are different from CSV file. Now the problem is that first I want to update column name of CSV file with database table headers and then import its data with field mapping into database.
Please help me I don't know how I can solve this.
This is my php code:
$file = $_POST['fileName'];
$filename = "../files/" . $file;
$list = $_POST['str'];
$array_imp = implode(',', $list);
$array_exp = explode(',', $array_imp);
$fp = fopen("../files/" . $file, "w");
$num = count($fp);
for ($c = 0; $c < $num; $c++) {
if ($fp[c] !== '') {
fputcsv($fp, $array_exp);
}
}
fclose($fp);
require_once("../csv/DataSource.php");
$path = "../files/test_mysql.csv";
$dbtable = $ext[0];
$csv = new File_CSV_DataSource;
$csv->load($path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{ print_r($key[1]);
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into tablename($myKey)values($myVal)";
$res= mysql_query($query);
You have got an existing file of which the first line needs to be replaced.
This has been generally outlined here:
Overwrite Line in File with PHP
Some little explanation (and some tips that are not covered in the other question). Most often it's easier to operate with two files here:
The existing file (to be copied from)
A new file that temporarily will be used to write into.
When done, the old file will be deleted and the new file will be renamed to the name of the old file.
Your code does not work because you are already writing the new first line into the old file. That will chop-off the rest of the file when you close it.
Also you look misguided about some basic PHP features, e.g. using count on a file-handle does not help you to get the number of lines. It will just return 1.
Here is step by step what you need to do:
Open the existing file to read from. Just read the first line of it to advance the file-pointer (fgets)
Open a new file to write into. Write the new headers into it (as you already successfully do).
Copy all remaining data from the first file into the new, second file. PHP has a function for that, it is called stream_copy_to_stream.
Close both files.
Now check if the new file is what you're looking for. When this all works, you need to add some more steps:
Rename the original file to a new name. This can be done with rename.
Rename the file you've been written to to the original filename.
If you want, you then can delete the file you renamed in 5. - but only if you don't need it any longer.
And that's it. I hope this is helpful. The PHP manual contains example code for all the functions mentioned and linked. Good luck. And if you don't understand your own code, use the manual to read about it first. That reduces the places where you can introduce errors.
If you are managing to insert the table headers then you're half way there.
It sounds to me like you need to append the data after the headers something like:
$data = $headers;
if($fp[c]!=='')
{
$data .= fputcsv($fp, $array_exp);
}
Notice the dot '.' before the equals '=' in the if statement. This will add none blank $fp[c]values after the headers.
Related
I have created a form that submits the data to a filename on the server. The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly. I have tried moving the code around but I'm still obviously missing something. The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>
Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");
The results of the above give me a filename called:
"wed_Import_[JaneBill].sts. I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.
If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like #Jay_P says
Why you don't name the file before writing to it?
<?php
$gfirstname = $_POST['gname'];
$bfirstname = $_POST['bname'];
$file = 'wed_input_Bride_Groom.sts';
// Opens the file to get existing content hopefully
$current = file_get_contents($file);
// Appends bride and groom first names to the file hopefully
$current .= ("gfirstname" . "bfirstname");
$new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
// Write the contents back to the file
file_put_contents($new_file, $current);
?>
Let's assume you have the names in a variable called $names. You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);
so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.
This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
Hi I want to append a row at the beginning of the file using php.
Lets say for example the file is containing the following contnet:
Hello Stack Overflow, you are really helping me a lot.
And now i Want to add a row on top of the repvious one like this:
www.stackoverflow.com
Hello Stack Overflow, you are really helping me a lot.
This is the code that I am having at the moment in a script.
$fp = fopen($file, 'a+') or die("can't open file");
$theOldData = fread($fp, filesize($file));
fclose($fp);
$fp = fopen($file, 'w+') or die("can't open file");
$toBeWriteToFile = $insertNewRow.$theOldData;
fwrite($fp, $toBeWriteToFile);
fclose($fp);
I want some optimal solution for it, as I am using it in a php script. Here are some solutions i found on here:
Need to write at beginning of file with PHP
which says the following to append at the beginning:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
And other one here:
Using php, how to insert text without overwriting to the beginning of a text file
says the following:
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
So my final question is, which is the best method to use (I mean optimal) among all the above methods. Is there any better possibly than above?
Looking for your thoughts on this!!!.
function file_prepend ($string, $filename) {
$fileContent = file_get_contents ($filename);
file_put_contents ($filename, $string . "\n" . $fileContent);
}
usage :
file_prepend("couldn't connect to the database", 'database.logs');
My personal preference when writing to a file is to use file_put_contents
From the manual:
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
Because the function automatically handles those three functions for me I do not have to remember to close the resource after I'm done with it.
There is no really efficient way to write before the first line in a file. Both solutions mentioned in your questions create a new file from copying everything from the old one then write new data (and there is no much difference between the two methods).
If you are really after efficiency, ie avoiding the whole copy of the existing file, and you need to have the last inserted line being the first in the file, it all depends how you plan on using the file after it is created.
three files
Per you comment, you could create three files header, content and footer and output each of them in sequence ; that would avoid the copy even if header is created after content.
work reverse in one file
This method puts the file in memory (array).
Since you know you create the content before the header, always write lines in reverse order, footer, content, then header:
function write_reverse($lines, $file) { // $lines is an array
for($i=count($lines)-1 ; $i>=0 ; $i--) fwrite($file, $lines[$i]);
}
then you call write_reverse() first with footer, then content and finally header. Each time you want to add something at the beginning of the file, just write at the end...
Then to read the file for output
$lines = array();
while (($line = fgets($file)) !== false) $lines[] = $line;
// then print from last one
for ($i=count($lines)-1 ; $i>=0 ; $i--) echo $lines[$i];
Then there is another consideration: could you avoid using files at all - eg via PHP APC
You mean prepending. I suggest you read the line and replace it with next line without losing data.
<?php
$dataToBeAdded = "www.stackoverflow.com";
$file = "database.txt";
$handle = fopen($file, "r+");
$final_length = filesize($file) + strlen($dataToBeAdded );
$existingData = fread($handle, strlen($dataToBeAdded ));
rewind($handle);
$i = 1;
while (ftell($handle) < $final_length)
{
fwrite($handle, $dataToBeAdded );
$dataToBeAdded = $existingData ;
$existingData = fread($handle, strlen($dataToBeAdded ));
fseek($handle, $i * strlen($dataToBeAdded ));
$i++;
}
?>
I have the following PHP code that checks which choice from a radio button was selected and then write to a file of the same name.
For example, from a Radio button group called "instrument", where the 4 choices are
Wind
Strings
Percussion
Vocal
If the user selects "Wind", then it would create and write to a file called "wind_instrument.txt". If "strings" is selected it would create the file "string_instrument.txt" and so on.
Here is my PHP code:
if ($_POST['instrument'] == "wind")
{
$lines = file('wind_instrument.txt');
$fopen = fopen("wind_instrument.txt", "w+");
}
elseif ($_POST['instrument'] == "strings")
{
$lines = file('strings_instrument.txt');
$fopen = fopen("strings_instrument.txt", "w+");
}
elseif ($_POST['instrument'] == "percussion")
{
$lines = file('percussion_instrument.txt');
$fopen = fopen("percussion_instrument.txt", "w+");
}
elseif ($_POST['instrument'] == "vocal")
{
$lines = file('vocal_instrument.txt');
$fopen = fopen("vocal_instrument.txt", "w+");
}
Now, if one of the conditions is met, would then go on to the next step in my code, being:
fwrite($fopen, ("Instrument: ")."");
fwrite($fopen, $_POST["instrument"]."\n");
fwrite($fopen, ("<br>")."\n");
The problem I have with this, is that it is not creating a file, and I do have permissions set.
Any help will be greatly appreciated, thank you.
You actually could do some refactoring in order to make it easier to maintain, nevertheless that wasn't your problem but I shall try to help you out.
<?php
$instruments = array('wind', 'strings', 'percussion', 'vocal');
if (in_array($_POST['instrument'], $instruments))
{
$instrument = $_POST['instrument'];
$file_handle = fopen($instrument.'_instrument.txt', 'a+');
$line = 'Instrument: '.$instrument."\n";
fwrite($file_handle, $line);
}
?>
The important thing to know is how I open the file. I use the mode a+. The documentation says
Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
Hope that helps.
If you've verified that you have permissions to open and write to a file, then there should be no problem with doing it based on a conditional. I suggest checking the contents of $_POST and making sure that instrument is present and meets one of your conditions. Alternately, you could add an else clause that will write the submission to an error file if no valid instrument was received. If that works, it would confirm that the problem is with the POSTed variable, not with fopen/fwrite.
If the options you provided in the bulleted list are the literal values of your radio buttons, then your problem is that they're capitalized and the values you test in the if statement aren't. Either capitalize them consistently, or use strtolower() to convert everything to a consistent case before comparing.
Is it possible to write at a particular location in a CSV file using PHP?
I don't want to append data at the end of the CSV file. But I want to add data at the end of a row already having values in the CSV.
thanks in advance
No, it s not possible to insert new data in the middle of a file, due to filesystem nature.
Only append at the end is possible.
So, the only solution is to make another file, write a beginning part of source, append a new value, and then append the rest of the source file. And finally rename a resulting file to original name.
There you go. Complete working code:
<?php
//A helping function to insert data at any position in array.
function array_insert($array, $pos, $val)
{
$array2 = array_splice($array, $pos);
$array[] = $val;
$array = array_merge($array, $array2);
return $array;
}
//What and where you want to insert
$DataToInsert = '11,Shamit,Male';
$PositionToInsert = 3;
//Full path & Name of the CSV File
$FileName = 'data.csv';
//Read the file and get is as a array of lines.
$arrLines = file($FileName);
//Insert data into this array.
$Result = array_insert($arrLines, $PositionToInsert, $DataToInsert);
//Convert result array to string.
$ResultStr = implode("\n", $Result);
//Write to the file.
file_put_contents($FileName, $ResultStr);
?>
Technically Col. Shrapnel's answer is absolutely right.
Your problem is that you don't want to deal with all these file operations just to change some data. I agree with you. But you're looking for the solution in a wrong level. Put this problem in a higher level. Create a model that represents an entity in your CSV database. Modify the model's state and call its save() method. The method should be responsible to write your model's state in CSV format.
Still, you can use a CSV library that abstracts low level operations for you. For instance, parsecsv-for-php allows you to target a specific cell:
$csv = new parseCSV();
$csv->sort_by = 'id';
$csv->parse('data.csv');
# "4" is the value of the "id" column of the CSV row
$csv->data[4]['firstname'] = 'John';
$csv->save();