Import csv file into Database

Hi a new one for me.
I need to import a .csv file into a DB table, from within my SC application, a process my client has requested.
I have not done this before and was hoping someone has done something similar and could point me in the right direction, and give me some guidance.
Thanks, anticipating your help.
Andy

Make a Control application, give it 2 fields: file(Document: file name) and message (Label)

On VALIDATE event:

// Starts array of File
$arr_file = array();
////
$path = $this->Ini->path_doc;
// Absolute path of the file
$file = $path . ‘/’ . {file};
$handle = fopen($file, ‘r’);
////
if(is_file($file))
{
// auto detect line endings
ini_set(“auto_detect_line_endings”, true);
///
$arr_file = file($file);
while(!feof($handle))
{
// handle each line of the CSV
$arr_line = fgetcsv($handle);
//var_dump($arr_line);

	$skip_line = false;
	// check to see if this is a header row
	if(empty($arr_line[1]))
	{
		$skip_line = true;
	}
	
	if($skip_line == false) 
	{
		$sql = "INSERT INTO tableName(column1,column2,column3,column4) VALUES ('";
	$sql .= trim(addslashes($arr_line[0])) . "', '";//field1 from CSV

$sql .= trim(addslashes($arr_line[1])) . “’, '”;//field2 from CSV
$sql .= trim(addslashes($arr_line[2])) . “’, '”;//field3 from CSV
$sql .= trim(addslashes($arr_line[3])). “’)”;//field4 from CSV
sc_exec_sql($sql);
// echo"$sql
";
}
}

else

{
// not a file
{message} .= " That is not CSV file!";

}
}
else
{
echo “YOU GOT LOGGED OUT!”;
}

1 Like

That’s great, thank you, I will take a good look tomorrow and make sure I understand it.

1 Like