【发布时间】:2018-01-04 11:44:42
【问题描述】:
我有两个数据库表,即photos、albums。我可以一次上传照片并将表单数据插入两个表中,这没关系。
我的问题是,
例如,当我上传 5 张照片时,每个表中会创建 5 行 - 每张照片的每一行。
我想要的是,
应该在photos 表中创建5 行但只有一行 应该进入albums 表。 photos 表具有 foreign key 到 albums 表。
下面是我的代码:
扩展UploadHandler 处理程序的index.php 具有以下代码:
<?php
$options = array(
'delete_type' => 'POST',
'db_host' => 'localhost',
'db_user' => 'username',
'db_pass' => 'password',
'db_name' => 'test',
'db_table' => 'photos'
);
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler {
protected function initialize() {
$this->db = new mysqli(
$this->options['db_host'],
$this->options['db_user'],
$this->options['db_pass'],
$this->options['db_name']
);
parent::initialize();
$this->db->close();
}
protected function handle_form_data($file, $index) {
$file->title = @$_REQUEST['title'][$index];
$file->description = @$_REQUEST['description'][$index];
}
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = parent::handle_file_upload(
$uploaded_file, $name, $size, $type, $error, $index, $content_range
);
if (empty($file->error)) {
$sql = 'INSERT INTO `'.$this->options['db_table']
.'` (`name`, `size`, `type`, `title`, `description`)'
.' VALUES (?,?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'sisss',
$file->name,
$file->size,
$file->type,
$file->title,
$file->description,
);
$query->execute();
$file->id = $this->db->insert_id;
//LABEL: PROBLEM BLOCK BEGINS
/*Here, I am attempting to insert only row in the albums table
for each batch of photos I upload. So even if I upload 5 photos
into the photos table, only one row should be created in the albums table*/
$sql2 = 'INSERT INTO `albums` (`album_title`, `album_description`)'
.' VALUES (?,?)';
$query2 = $this->db->prepare($sql2);
$query2->bind_param(
'ss',
$file->title,
$file->description,
);
$query2->execute();
$file->id = $this->db->insert_id;
//LABEL: PROBLEM BLOCK ENDS
}
return $file;
}
}
$upload_handler = new CustomUploadHandler($options);
?>
在上面的代码中,我将代码块注释为
//LABEL: PROBLEM BLOCK BEGINS
...
//LABEL: PROBLEM BLOCK ENDS.
上面的代码可以在photos 表和albums 表中插入相同数量的行。我需要PROBLEM BLOCK 的帮助,以便为我在照片表中上传的每批photos 在albums 表中创建一行。
【问题讨论】:
-
也许这是您对问题所做的更改,但我认为 second_table 不应该有单引号?
-
@astrangeloop,是的,你是对的。我已经编辑并删除了
second_table中的单引号 -
我已将
first_table重命名为photos并将second_table重命名为albums,以使问题的概念更加清晰和具体。
标签: php mysql jquery-file-upload blueimp