Is it possible to build a dynamic insert statement from an array? I have a 62-field table into which I want to insert data from a CSV file with delimiter |. I wanted to avoid writing a huge insert statement by hand - especially when I may end up coding this to check for particular file prefixes to go into their own table with different form fields (CIB into table A, RES into table B, etc.). I was hoping there may be a way to dynamically generate something akin to $field[0], $field[1] (count the array fields and numerically assign in order) to go into field1, field2, etc. (where we don't know the table names, but we can dump field[0] into the very first field of the table, field[1] into the second and so on) of this particular table.
I've gotten each piece of data into its own array using the code at the bottom, which outputs many arrays like the following:
Array ( [0] => 13641 [1] => COLDWELL BANKER REAL ESTATE [2] => 534054 [3] => 1886 [4] => [5] => Big Sewickley Creek [6] => 99900 [7] => C [8] => NAL [9] => 104004 [10] => ST [11] => CNT [12] => 2.3 [13] => 57500 [14] => office/restrt [15] => Tavern/rest [16] => 8 [17] => CON [18] => [19] => n [20] => [21] => [22] => [23] => [24] => [25] => BUS [26] => BLD [27] => EQ [28] => LD [29] => [30] => n [31] => 93 [32] => [33] => [34] => U [35] => [36] => [37] => [38] => 93x1079x93x1079 [39] => [40] => [41] => [42] => 30 [43] => offstree [44] => n [45] => n [46] => [47] => RLND [48] => REST [49] => [50] => G [51] => E [52] => W [53] => S [54] => [55] => [56] => [57] => [58] => 999 [59] => 15143 [60] => M1 [61] => 212918 [62] => Information Deemed Reliable, But Not Guaranteed )
# get data files in an array and insert data into data table
foreach($filestructure as $key => $value) {
//if it ends in txt, we'll perform these actions on them
if ($value['extension'] == 'txt') {
foreach($value as $key2 => $value2) {
//get name of each data file and assign its path
$datafile_path = $path."/".$value['name'];
//open the file for reading
$fd = fopen ($datafile_path, "r");
$contents = fread ($fd,filesize ($datafile_path));
fclose ($fd);
$delimiter = "\n";
//explode into array
$splitcontents = explode($delimiter, $contents);
$counter = "";
//read through array
foreach ( $splitcontents as $key => $value )
{
$delimiter = "|";
$contentsarray = explode($delimiter, $value);
//split yet again so we can put pieces into DB
foreach ( $contentsarray as $key2 => $value2 )
{
# build dynamic insert statement here
print_r($contentsarray);
}
}
}
}
}
I didn't think seralize was what I wanted to use for this application, as I want to allow reasonable quick searches from the data.
Also, this is not a 'form'; it's written as part of a 'cleanup' PHP cron script that will read a directory, unzip certain files, find certain text files, suck the data out each text file, dump it into the database, then delete the text file. It is as yet incomplete (needs error checking and such).