I've found a bit of solution for my last question:Trouble inserting data from csv into mysql database with unknown number of columns , so let me explain whats my problem now. Since users of my app can make custom columns in tables of my database, I've found a way to store number and names of columns by running this query:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name='$tblname'"
And I stored result in $anotherArray
variable. Now, since my users have option to import CSV
files into their custom tables(with custom number of columns) I did this:
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$name = $_FILES['file']['name'];
if (strrpos($name, '.csv', -4)) {//recognises if uploaded file is .csv
do {
if ($data[0]) {
$query = "INSERT INTO $tabela (";
$last = end($anotherArray);//$anotherArray holds names and number of columns user have made
foreach ($anotherArray as $something) {
if ($something != $last) {
$query .= "" . $something . ",";
} else {
$query .= "" . $something . ")";
}
}
$query .= "VALUES (";
So since the uploaded csv file will look something like this:
Please note again that this is a testing file, and some user will maybe make 9 custom columns in his table and his document will have 9 values within one row of csv file. I made this part of script to make an array out of values of that csv:
$lengtara = count($anotherArray);
$length1 = count($data);//$data is array with csv file values
$nizDuzina = count($anotherArray);
$restructured1 = [];
for ($i = 0; $i < $length1; $i += $nizDuzina) { // note the $i+=$nizDuzina increments $i by number of columns in database table.
for ($j = 0; $j < $nizDuzina; $j++) {
$restructed1 [$j] = $data[$i + $j];//this is a key thing in my script!
}
}
}
}
while ($data = fgetcsv($handle, 1000, ",", "'")) ;
$query = rtrim($query, ',');
$query .= ")";
//var_dump($query);
$rez = $mysqli->query($query);
So when I do print_r($restructed1)
I get an array like this:
Array ( [0] => 123123123 [1] => Ognjen [2] => Babic ) Array ( [0] => 23423423 [1] => Neven [2] => Babic ) Array ( [0] => 235646345 [1] => Vanja [2] => Babic ) Array ( [0] => 4853424 [1] => Nikola [2] => Babic ) Array ( [0] => 34545747 [1] => Viktor [2] => Sovilj )
NOW this is a key point of my question: How to import array like this into a database, but in some dynamic, general way, so it can suit for exaple if arrays within my array has 2 or 7 elements both?