Jump to content

Help with form & CSV import to mysql


ja_blackburn

Recommended Posts

Hello

 

I am trying to do a simple CSV import of a file and then upload to mysql. I am basing my code on an example I have found and I am getting the error message 'invalid file'. The example used includes a text box for the file import field and I am referencing the file from my computer in that box 'Users/James/name.csv'

 

My code is as follows:

 

HTML

 

        <form action="results.php?data=upload" method='post'>

 

    Import File : <input type='text' name='sel_file' size='20'>

    <input type='submit' name='submit' value='submit'>

 

        </form>

 

PHP

 

        if ($b == 'upload') {

    $fname = $_FILES['sel_file']['name'];

 

    $chk_ext = explode(".",$fname);

 

    if(strtolower($chk_ext[1]) == "csv")

    {

 

        $filename = $_FILES['sel_file']['tmp_name'];

        $handle = fopen($filename, "r");

 

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)

        {

            $sql = "INSERT into ".$db['name']."(field1,field2,field3,field4) values('$data[0]','$data[1]','$data[2]', '$data[3]')";

            mysql_query($sql) or die(mysql_error());

        }

 

        fclose($handle);

        echo "Successfully Imported";

    }

    else

    {

        echo "Invalid File";

    }

}

 

my file format is:

 

1,23,1,5

1,24,2,5

1,25,3,5

1,26,4,5

1,27,5,5

1,28,6,5

1,29,7,5

1,30,8,5

1,31,9,5

1,32,10,5

 

If anybody can help that would be good - or perhaps point out if I am going about this the wrong way - cheers

Link to comment
Share on other sites

Still waiting for the caffeine to kick in, so untested and un-proof-read but:

 

Try changing your form to this...

<form enctype="multipart/form-data" action="results.php" method="POST">
<input type="hidden" name="data" value="upload" /> 
Choose a file to upload: <input name="sel_file" type="file" /><br />
<input type="submit" value="submit" /> 
</form> 

 

and your results.php to this...

<?PHP
$data = trim($_POST['data']);
if($data !="upload") {
/* trap */
exit();
}
$filename = $_FILES['sel_file']['name'];
$chk_ext = explode(".",$filename);
if(strtolower($chk_ext[1]) != "csv"){
/* trap */
exit();
}
if(move_uploaded_file($_FILES['sel_file']['name'], $filename)) {
} else{ 
echo "There was an error uploading the file, please try again!"; 
exit();
} 
$lines = file($filename);
include('db.php'); /* connect to db here */
$i=0;
$x=count($lines);
$table_name = "sometablename";
while ($i<$x) {
$temp_data = explode(",", $lines[$i]);
$field1= $temp_data[0];
$field2= $temp_data[1];
$field3= $temp_data[2];
$field4= $temp_data[3];
$sql = "INSERT into ".$table_name."(field1,field2,field3,field4) values('$field1','$field2','$field3','$field4')";
$result = mysql_query($sql) or die(mysql_error());
}
?>

Link to comment
Share on other sites

Hi, thanks for the reply..

 

I have slightly modified the form code as the framework I use will need the form to be posted back to itself, controlling the path by an if statement at the stop:

 

            <form enctype="multipart/form-data" action="results.php?data=upload" method="POST">

            <input type="hidden" name="data" value="upload" />

            Choose a file to upload: <input name="sel_file" type="file" /><br />

            <input type="submit" value="submit" />

            </form>

 

The following code is at the top of the page:

 

if ($b == 'upload') {

 

    $data = trim($_POST['data']);

if($data !="upload") {

/* trap */

exit();

}

$filename = $_FILES['sel_file']['name'];

$chk_ext = explode(".",$filename);

if(strtolower($chk_ext[1]) != "csv"){

/* trap */

exit();

}

if(move_uploaded_file($_FILES['sel_file']['name'], $filename)) {

} else{

echo "There was an error uploading the file, please try again!";

exit();

}

$lines = file($filename);

//include('db.php'); /* connect to db here (don't need to do this part as I am already calling in a function */

$i=0;

$x=count($lines);

$table_name = "or_results";

while ($i<$x) {

$temp_data = explode(",", $lines[$i]);

$field1= $temp_data[0];

$field2= $temp_data[1];

$field3= $temp_data[2];

$field4= $temp_data[3];

$sql = "INSERT into ".$db['results']."(sub_event_id,race_no,position_no,time) values('$field1','$field2','$field3','$field4')";

 

$result = mysql_query($sql) or die(mysql_error());

}

 

    }

 

 

Coming back with error message "There was an error uploading the file, please try again!"

 

Any ideas? I may be doing something wrong around the part i have put in italics!

 

Help greatly appreciated.

 

Link to comment
Share on other sites

where is $b set? have you tested it to see what value it holds?

 

an easy way to eliminate errors is to ALWAYS check variable content using values you KNOW, when those variables are used in conditional statements. That way you can isolate more closely the point of failure

Link to comment
Share on other sites

Hi,

 

I have used this method for a recent tests that I have made. It uses fgetcsv php function.

 

public function insertLinesToDb($input_csv_file, $db_table) {

	// Vou assignar o valor do $this->input_csv_file
	$this->input_csv_file = $input_csv_file;

	// Vou apontar para a primeira linha
	$row = 1;

	// Vou apanhar as linhas com dados
	if (($handle = fopen($this->input_csv_file, "r")) !== FALSE) {
		while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

			// Para todas as outras linhas que não a primeira
			if ($row >=2) {
				$fields = implode("', '", $data);
				$fields_final = "('" . $fields . "');";

			// Vou inserir para a BD. Aqui nesta linha vou ter de chamar um método do model do CodeIgniter!!!!!!!!!!!!!!!
			echo "INSERT INTO " . $db_table . " (" . $this->obtainHeader() . ") VALUES " . $fields_final;
			}	 

			// Vou passar para a próxima linha
			$row = $row + 1;
		}
		fclose($handle);
	}
	return 0;
}

 

Feel free to adapt to MySQL  and to your framework.

Link to comment
Share on other sites

for testing purposes only, place this code just BEFORE

 

if ($b == 'upload') {

 

$target_path = "uploads/"; /* change this to the path you are using */
$target_path = $target_path . basename( $_FILES['sel_file']['name']); 
if(move_uploaded_file($_FILES['sel_file']['tmp_name'], $target_path)) { 
echo "The file ". basename( $_FILES['sel_file']['name']). " has been uploaded"; 
} else{ 
echo "There was an error uploading the file, please try again!"; 
} 
exit();

 

Link to comment
Share on other sites

If i put the code before the

 

if ($b == 'upload') {

 

I get an error as no value has been passed to it.

 

 

I have tried your code inside the if statement and commented out everything else, and the file was uploaded successfully... a glimmer of hope  :-*

 

Thanks for your continued support - the first time I have written something to do this...

 

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.