Jumat, 04 Januari 2019

Joomla 3.x Import CSV file to Joomla Database

Below is the codes inserted in the controller, with function called "import_from_file".

function import_from_file()
{
$validate = 1;//default success -- meanwhile dont do anything
$message = JText::_('COM_TESTDATA_SUCCESSFUL_POST');//default message - cc change component

//validation process below is working 28/12

$columns = array();
$values = array();
$row = 1;
if (($handle = fopen("tmp/dataw.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data); //$num = number of columns or fields
if($row == 1){ //as header, then array per item
for ($c=0; $c < $num; $c++) { // $cs = field in a record
$disp = $data[$c]; //just to make some data displayed.
array_push($columns, $data[$c]); // first row is treated as headers
}
$row++; // go to next record
}
else{
$imploded ="'". implode("','", $data) ."'";// patch a bit, if no '' then sometimes error in joomla
array_push($values, $imploded);
}
}
}
fclose($handle);


$arrlength = count($columns);
for($x = 0; $x < $arrlength; $x++) {
echo $columns[$x];
echo "<br>";
}


if($validate == 1){

try {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->insert($db->quoteName('#__testdata'));
$query->columns($columns); //set columns headers
$query->values($values); // insert the values here.
$db->setQuery($query);
$db->query();
$message = 'Success!'; //need to work on this later.
echo $validate;
}
catch (Exception $e) {
$message = 'Caught exception: '.  $e->getMessage();
}
}


parent::display($cachable = false, $urlparams = false);
}

Tidak ada komentar: