Getting Excel row data to mysql column in php

对着背影说爱祢 提交于 2019-12-13 08:29:52

问题


I know how I can get data from excel to mysql using php. Please have look at the excel chart below:

I want to input data in below mysql table. From the excel file column D,E,F,G data will insert as row in mysql table & column A,B,C & H will input as column but will follow the no of row as A,B,C & D

I feel what I'm asking is a bit complicated. But please try to give some idea or advise on how to do that. I can't change the excel file, because there are many files to proceed this way.


回答1:


Basically one row from Excel will insert/update 4 rows in MySQL. May use PhpSpreadsheet for an easy iteration of Excel file.

The logic in in pseudo-php-code will be something like:

For inserts only:

// Statement prepare
$DB = new PDO('mysql:host='.$host.';dbname='.$base., $user, $pass);
$ST = $DB->prepare('insert into table(field1, fiel2, ..) values (:field1, :field2, ..)');

// Excel iteration
while ($Row = $Excel->NextRow()) {
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['D']]);
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['E']]);
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['F']]);
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['G']]);
}

For synchronization:

// Statement prepare
$DB = new PDO('mysql:host='.$host.';dbname='.$base., $user, $pass);
// Update statement
$ST = $DB->prepare('update table set field2 = :field2 where field1 = :field2 and ..)');

// Excel iteration
while ($Row = $Excel->NextRow()) {
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['D']]);
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['E']]);
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['F']]);
  $ST->execute(['field1' => $Row['A'], .. 'field2' => $Row['G']]);
}

Hope you got the idea.




回答2:


Here below the code,its fine now.

$fft1=888;
$fft2=777;
$fft3="";
$fft4=999;

$fft5=100;
$ctnqty=10;
$friendslist = "$fft1,$fft2,$fft3,$fft4";
$id = $fft5;
$friendarray = explode(",", $friendslist);
  $frienduserarray = array();

for ($n = 0; $n < count($friendarray); $n++) {
  $friendidpush = "('".$id."','".$friendarray[$n]."','".$ctnqty."'),";
  array_push($frienduserarray, $friendidpush);
 }
 $query = "INSERT INTO freddyhipment (style, orderno,ctnqty) VALUES ";
 $friendarray = explode(",", $friendslist);

 foreach ($friendarray as $order) {
$query .= "('" . $id . "','" . $order . "','" . $ctnqty . "'),";
}

$query = substr($query, 0, -1); // remove trailing comma


来源:https://stackoverflow.com/questions/46432063/getting-excel-row-data-to-mysql-column-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!