PHP Classes

Howto load a database_table from CSV using Absinter class

Recommend this page to a friend!

      Absint PHP Template Engine Trait  >  All threads  >  Howto load a database_table from CSV...  >  (Un) Subscribe thread alerts  
Subject:Howto load a database_table from CSV...
Summary:An example to load a database_table from CSV
Messages:1
Author:wim niemans
Date:2021-01-07 16:11:51
 

  1. Howto load a database_table from CSV...   Reply   Report abuse  
Picture of wim niemans wim niemans - 2021-01-07 16:11:51
My first contribution was about a quick'n dirty conversion of a relational table to a CSV file.
The opposite route is simple too and looks very similar.
We'll use the Absinter class for this example, too.

Assume your sql looks like 'REPLACE INTO {table} VALUES {properties}'.
The minimaal config is now taken from the first csv_row:
$csv_rows = @get_file(($file_name);
$csv_header = array_shift($csv_rows);
$properties = explode ("','", trim($csv_header, "'"));

$table = 'my_relational_table';
$sql = 'REPLACE INTO ' . $table . '(' . join(', ', $properties) . ')'
. ' VALUES ' . "({'" . join("}, {", $properties) . "});");

$absinter = new Absinter();
foreach ($csv_rows as $csv_row) {
$columns = explode("','", trim($row, "'"));
$row = array_combine($properties, $columns); // combine keys and values
$dbQuery($absinter->parse($sql, $row));
}