我需要在Opencart中的Opencart产品插入/添加表单中,将自定义文件输入字段添加到它自己的选项卡中,以将csv文件上传到mysql数据库中。我已经将选项卡/字段添加到视图文件中,更新了语言文件,但不确定我需要在控制器和模型中做什么,以便将上传的csv中的数据传递到数据库表中。
product_pins
表:
pin_id (AI) | pin_product_id | pin_pin_number
csv文件数据(示例):
342353535345
345345346346
235434534634
到目前为止我所处的位置:
控制器admin/controller/catalog/product.php
(在线807附近):
if (isset($this->request->post['product_pins']) ) {
$this->data['product_pins'] = is_uploaded_file($this->request->post['product_pins']);
} else {
$this->data['product_pins'] = '';
}
型号admin/model/catalog/product.php
(7号线附近):
if ( isset($this->data['product_pins']) ) {
$handle = fopen($this->data['product_pins'], "r");
while (($pins = fgetcsv($handle, 1000, ",")) !== false) {
foreach ($pins as $pin) {
$this->db->query("INSERT INTO " . DB_PREFIX . "product_pins SET pin_product_id = '" . (int)$product_id . "', pin_pin_number = '" . $this->db->escape($pin) . "'");
}
}
fclose($handle);
}
如果有任何帮助,我将不胜感激。
首先,CSV处理部分应该在控制器中,而不是在模型类中。模型(当谈到正确的MVC时)应该只检索或设置数据,并将它们传递给或从控制器传递——然后控制器应该操纵和控制它们,并转发到前端视图(模板)或从前端视图获得。
其次:OpenCart中提交的文件存在于$this->request->files
数组中。
最后:方法is_uploaded_file()
返回boolean
值,因此我不知道你如何解析boolean
并从中创建一个文件句柄
所以,让我们来看看它…试试下面的代码。
控制器:
if (is_uploaded_file($this->request->files['product_pins']['tmp_name'])) {
$handle = fopen($this->request->files['product_pins']['tmp_name'], "r");
while (($pins = fgetcsv($handle, 50, ",")) !== false) { // If we know there is only a 10 chars PIN per line it is better to lower the expected line length to lower the memory consumption...
$this->data['product_pins'][] = $pins; // there is only one PIN per line
}
fclose($handle);
} else {
$this->data['product_pins'] = array();
}
现在,您(应该)已经将CSV文件中的所有PIN添加到$this->data['product_pins']
数组中,并且假设您正在将$this->data
传递给模型,它应该包含以下代码:
型号:
if (!empty($this->data['product_pins'])) {
foreach ($this->data['product_pins'] as $pin) {
$this->db->query("INSERT INTO " . DB_PREFIX . "product_pins SET pin_product_id = '" . (int)$product_id . "', pin_pin_number = '" . $this->db->escape($pin) . "'");
}
}
希望这能帮助。。。