php - PHP 和 MySQL:多重上传时分开文件
问题描述
您好开发人员我需要有关功能的帮助。问题如下:
我正在将多张图片上传到数据库。处理表单时,php 脚本会收到如下数组:
var_dump($postdata):
array(2) { ["photo"]=> string(22) "wg2yi.jpg,l1b6c42j.jpg" ["album_id"]=> string(2) "15" }
执行 mysql 插入的脚本是这样的:
照片控制器.php
function add(){
if(is_post_request()){
Csrf :: cross_check();
$db = $this->GetModel();
$tablename = $this->tablename = 'photos';
$fields = $this->fields = array('foto','album_id'); //insert fields
$postdata = $this->transform_request_data($_POST);
$this->rules_array = array(
'photo' => 'required',
'album_id' => 'required',
);
$this->sanitize_array = array(
'photo' => 'sanitize_string',
'album_id' => 'sanitize_string',
);
$this->filter_vals = true; //set whether to remove empty fields
$modeldata = $this -> modeldata = $this->validate_form($postdata);
if(empty($this->view->page_error)){
$rec_id = $this->rec_id = $db->insert($tablename, $modeldata);
if(!empty($rec_id)){
if(is_ajax()){
render_json("Sucess!");
}
else{
set_flash_msg("Sucess!",'success');
if(!empty($this->redirect)){
redirect_to_page($this->redirect); //if redirect url is passed via $_GET
}
else{
redirect_to_page("photos");
}
}
return;
}
else{
$page_error = null;
if($db->getLastError()){
$page_error = $db->getLastError();
}
else{
$page_error = "Error";
}
if(is_ajax()){
render_error($page_error);
return;
}
else{
$this->view->page_error[] = $page_error;
}
}
}
}
$this->view->page_title ="Add new";
$this->view->render('photos/add.php' ,null,'main_layout.php');
}
使用上面的脚本上传多张图片,照片保存在一个唯一的行中,用逗号分隔,如下所示:
row photo =>
id => 1
photo => wg2yi.jpg, l1b6c42j.jpg //comma separated
album_id => 15
但是我需要将每个图像保存在不同的行:
row photo =>
id => 1
photo => wg2yi.jpg //first image
album_id => 15
id => 2
photo => l1b6c42j.jpg //second image
album_id => 15
我怎么做?我尝试在 PhotosController.php 上添加此代码以获取分离的照片: PhotosController.php
foreach ($postdata as $key => $val ) {
$getSeparatedItems= explode(',',$val);
foreach ($getSeparatedItems as $item) {
echo "<li>$item</li><hr>";
}
但我不能在不同的行上传图片。有人能帮我吗?
基本控制器.php
/**
* validate post array using gump library
* sanitize input array based on the page sanitize rule
* validate data based on the set of defined rules
* @var $filter_rules = true: will validate post data only for posted array data if field name is not set in the postdata
* @return Array
*/
function validate_form($modeldata){
if(!empty($this->sanitize_array)){
$modeldata = GUMP::filter_input($modeldata, $this->sanitize_array);
}
$rules = $this->rules_array;
if($this->filter_rules == true){
$rules = array(); //set new rules
//set rules for only fields in the posted data
foreach($modeldata as $key => $val){
if(in_array($key, $this->rules_array)){
$rules[$key] = $this->rules_array[$key];
}
}
}
//accept posted fields if they are part of the page fields
$fields = $this->fields;
if(!empty($fields)){
foreach($modeldata as $key => $val){
if(!in_array($key, $fields)){
unset($modeldata[$key]); //remove field if not part of the field list
}
}
}
$is_valid = GUMP::is_valid($modeldata, $rules);
// remove empty field values
if($this->filter_vals == true){
$modeldata = array_filter($modeldata, function($val){
if($val === "" || is_null($val)){
return false;
}
else{
return true;
}
});
}
if($is_valid !== true) {
if(is_array($is_valid)){
foreach($is_valid as $error_msg){
$this->view->page_error[] = strip_tags($error_msg);
}
}
else{
$this->view->page_error[] = $is_valid;
}
}
return $modeldata;
}
/**
* Concat Array Values With Comma if REQUEST Value is a simple Array
* Specific for this Framework Only
* @arr $_POST || $_GET data
* @return Array
*/
function transform_request_data($arr){
foreach($arr as $key=>$val){
if(is_array($val)){
$arr[$key]=implode(',',$val);
}
}
return $arr;
}
/**
* Concat Array Values With Comma for multiple post data
* Specific for this Framework Only
* @arr $_POST || $_GET data
* @return Array
*/
function transform_multi_request_data($arr){
$alldata = array();
foreach($arr as $key=>$value){
$combine_vals = recursive_implode($value, "");
//merge all values of each input into one string and check if each post data contains value
if(!empty($combine_vals)){
$alldata[] = $this -> transform_request_data($value);
}
}
return $alldata;
}
/**
* Init DB Connection
* Which can be use to perform DB queries
* @return PDO Object
*/
function GetModel(){
//Initialse New Database Connection
$this->db = new PDODb(DB_TYPE, DB_HOST , DB_USERNAME, DB_PASSWORD, DB_NAME, DB_PORT , DB_CHARSET);
return $this->db;
}
/**
* Delete files
* split file path if they are separated by comma
* @files Array
* @return nul
*/
function delete_record_files($files, $field){
foreach($files as $file_path){
$comma_paths = explode( ',', $file_path[$field] );
foreach($comma_paths as $file_url){
try{
$file_dir_path = str_ireplace( SITE_ADDR , "" , $file_url ) ;
@unlink($file_dir_path);
}
catch(Exception $e) {
// error_log('Message: ' .$e->getMessage());
}
}
}
}
/**
* upload files and return file paths
* @var $fieldname File upload filed name
* @return nul
*/
function get_uploaded_file_paths($fieldname){
$uploaded_files = "";
if(!empty($_FILES[$fieldname])){
$uploader = new Uploader;
$upload_settings = $this->file_upload_settings[$fieldname];
$upload_data = $uploader->upload($_FILES[$fieldname], $upload_settings );
if($upload_data['isComplete']){
$arr_files = $upload_data['data']['files'];
if(!empty($arr_files)){
if(!empty($upload_settings['returnfullpath'])){
$arr_files = array_map( "set_url", $arr_files ); // set files with complete url of the website
}
$uploaded_files = implode("," , $arr_files);
}
}
if($upload_data['hasErrors']){
$errors = $upload_data['errors'];
foreach($errors as $key=>$val){
$this->view->page_error[] = "$key : $val[$key]";
}
}
}
return $uploaded_files;
}
/**
* For getting uploaded file as Blob type
* can be use to insert blob data into the databased
* @var $fieldname File upload filed name
* @return Blob object
*/
function get_uploaded_file_data($fieldname){
if(!empty($_FILES[$fieldname])){
$name = $_FILES[$fieldname]['name'];
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$tmp_name = $_FILES[$fieldname]['tmp_name'];
$type = $_FILES[$fieldname]['type'];
$size = $_FILES[$fieldname]['size'];
return file_get_contents($tmp_name);
}
return null;
}
上传表单添加:
<form id="photos-add-form" role="form" novalidate enctype="multipart/form-data" class="form form-horizontal needs-validation" action="<?php print_link("photos/add?csrf_token=$csrf_token") ?>" method="post">
<div>
<div class="form-group ">
<div class="row">
<div class="col-sm-4">
<label class="control-label" for="foto">Add Photos <span class="text-danger">*</span></label>
</div>
<div class="col-sm-8">
<div class="">
<div class="custom-file">
<input class="custom-file-input" name="photo[]" id="ctrl-photo" filesize="6" multiple accept=".jpg,.png,.gif,.jpeg" filesize="6" maximum="12" required="" accept="" class="form-control" type="file" />
<label class="custom-file-label" for="ctrl-photo">[html-lang-0082]</label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group ">
<div class="row">
<div class="col-sm-4">
<label class="control-label" for="album_id">Album <span class="text-danger">*</span></label>
</div>
<div class="col-sm-8">
<div class="">
<select required="" id="ctrl-album_id" name="album_id" placeholder="Selecione um álbum ..." class="custom-select" >
<option value="">Select albumn ...</option>
<?php
$album_id_options = $comp_model -> fotos_album_id_option_list();
if(!empty($album_id_options)){
foreach($album_id_options as $option){
$value = (!empty($option['value']) ? $option['value'] : null);
$label = (!empty($option['label']) ? $option['label'] : $value);
$selected = $this->set_field_selected('album_id',$value, '');
?>
<option <?php echo $selected; ?> value="<?php echo $value; ?>">
<?php echo $label; ?>
</option>
<?php
}
}
?>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="form-group form-submit-btn-holder text-center">
<div class="form-ajax-status"></div>
<button class="btn btn-primary" type="submit">
Send
<i class="fa fa-send"></i>
</button>
</div>
</form>
解决方案
推荐阅读
- wordpress - 切换菜单按钮被链接标签包裹
- mysql - 查找与特定优惠券关联的所有订单
- android - Android:在列表视图中禁用元素上的 scolling
- android - 具有水平对齐和自动调整大小的 ConstraintLayout、TextView 和 ImageView
- python - python中多重继承的调用过程
- apache-spark - 结构化流式多水印
- javascript - Oracle Apex 19.1 - 按钮单击时的动态操作设置屏幕上的值将空值写入数据库
- python-3.x - [x]* 在 python 函数文档中是什么意思?
- css - CSS 到属性内的目标类
- python - 在 Pandas 的日期时间值列中混合日期和月份