0

I want to allow the user to select a file from which data is exported and saved into a database. I found the following code to import the data:

$fp = fopen("people.csv", "r");

while ($line = fgets($fp)) {
$char =  split("\t",$line,4); 
 list($name, $age,$height,$date) = $char;
//Split the line by the tab delimiter and store it in our list
$sql = "insert into people(name,age,height,date) values('$name','$age','$height','$date')"; // Generate our sql string
mysql_query($sql) or die(mysql_error()); // Execute the sql
//fclose($line);

I'm not sure if it works but i'm yet to get that far. My question is how do I get the full path name of the selected file so I can feed it into the following command rather than hard coding the filename:

$fp = fopen("people.csv", "r");

I have spent alot time researching this but to no avail.

batsta13
  • 549
  • 2
  • 12
  • 26

2 Answers2

0

If you want to let users upload this file, you should implement file upload. Please check W3Schools Tutorial for instructions.

The main idea is to get file path from $_FILES["file"]["tmp_name"]:

$fp = fopen($_FILES["file"]["tmp_name"], "r");

If you store your file statically in your web project folder, you can use the path including your DOCUMENT_ROOT:

$path = $_SERVER["DOCUMENT_ROOT"] + 'relative/path/to/your/file/' + 'people.csv'; 
Mikhail Chernykh
  • 2,659
  • 22
  • 15
  • Thanks for repsponding. If its possible I don't actually want to upload the file I just need the path of the file on the local machine. Is there any other way or do I have to upload the file and use the pathname of the file on the server. – batsta13 Mar 27 '13 at 22:24
  • @batsta13 To process the file with PHP, you should have this file on a server where your PHP interpreter is installed. You can upload file another way, then you should use the second approach with `DOCUMENT_ROOT` I've mentioned in my answer. – Mikhail Chernykh Mar 28 '13 at 09:16
0

You can obtain the path of the current file via the __DIR__ magic constant;

Magic constants

In your case;

echo __DIR__ . 'people.csv';

Also, you may consider using the built-in CSV functions that PHP offers; http://php.net/manual/en/function.fgetcsv.php

If you want to skip processing the file via PHP altogether, MySQL offers ways to directly import data from a CSV file;

https://dev.mysql.com/doc/refman/5.5/en/load-data.html

thaJeztah
  • 27,738
  • 9
  • 73
  • 92