PHP OOP中的多文件上传方法 [英] Multiple file upload method in PHP OOP

查看:139
本文介绍了PHP OOP中的多文件上传方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 PHP 中构建一个方法,将多个文件上传到 MySQL 数据库中,并将这些文件的名称插入

我正在尝试基于 PHP OOP 构建这个功能。

我遇到的多个问题而且我已经用这种方法进行了2周以上的治疗。 1行进入数据库即使我选择了多个文件的形式。



其次:方法没有获取文件名,所以即使如果只插入一行,它会插入一个空行。



这是 images类

 <?php 
class图片扩展Crud {
protected static $ db_table =images;
protected static table_fields = array(id,image_url,property_id,date);
public $ id;
public $ image_url;
public $ property_id;
public $ date;
public $ filename;
public $ tmp_path = array();
public $ upload_dir =images;
public $ errors = array();
public $ upload_errors_array = array(
UPLOAD_ERR_OK =>没有错误,
UPLOAD_ERR_INI_SIZE =>文件大小超过upload_max_filesize,
UPLOAD_ERR_FORM_SIZE => ;文件上传超过MAX_FILE_SIZE,
UPLOAD_ERR_PARTIAL =>上传的文件仅部分上传,
UPLOAD_ERR_NO_TMP_DIR =>缺少临时文件夹,
UPLOAD_ERR_CANT_WRITE => ;无法在桌面上写文件,
UPLOAD_ERR_EXTENSION =>PHP扩展停止文件上传
);

public function image_path(){
return $ this-> upload_dir.DS。$ this-> image_url;


public function set_files($ file){
if(empty($ file)||!$ file ||!is_array($ file)){
$ this-> errors [] =这里没有上传文件;
返回false;
} else {
$ this-> image_url = $ file ['name'];
$ this-> tmp_path = $ file ['tmp_name'];

$ b $ public function new_images(){
foreach($ _FILES ['images'] as $ file){
$ this-> set_files($文件);
$ this-> property_id =1;
$ this-> date = date('Y-m-d H:i:s');
$ target_path = $ this-> upload_dir。 DS。 $这 - > IMAGE_URL;
move_uploaded_file($ this-> tmp_path,$ target_path);
if($ this-> create()){
print_r($ file);
var_dump($ file);
返回true;
}
}
}
}
?>

print_r 显示以下:

 数组([0] =>下载(1).jpg [1] =>下载(2).jpg [2] =>下载(3).jpg [3] => download.jpg)

var_dump 显示以下内容:

  array(4){[0] =>字符串(16)download(1).jpg[1] => string(16)download(2).jpg[2] =>字符串(16)download(3).jpg[3] => string(12)download.jpg} 

更多详情



以下是 images class class 的主要类:

 <?php 
class Crud {
protected static $ db_table;
public static function find(){
return static :: find_query(SELECT * FROM。static :: $ db_table。);

public static function find_limit($ limit){
return static :: find_query(SELECT * FROM。static :: $ db_table。LIMIT。$ limit。) ;

public static function find_id($ id){
global $ database;
$ the_result_array = static :: find_query(SELECT * FROM。static :: $ db_table。WHERE id ='$ id');
return!empty($ the_result_array)? array_shift($ the_result_array):false;

public static function find_query($ sql){
global $ database;
$ set_result = $ database-> query($ sql);
$ object_array = array();
while($ rows = mysqli_fetch_array($ set_result)){
$ object_array [] = static :: instantiation($ rows);
}
return $ object_array;

public static function instantiation($ records){
$ calling_class = get_called_class();
$ object = new $ calling_class;
foreach($ records as $ attribute => $ value){
if($ object-> has_attribute($ attribute)){
$ object-> $ attribute = $ value ;
}
}
return $ object;

私有函数has_attribute($属性){
$ object_properties = get_object_vars($ this);
返回array_key_exists($ attribute,$ object_properties);

保护函数属性(){
$ properties = array();
foreach(static :: $ table_fields as $ field){
if(property_exists($ this,$ field)){
$ properties [$ field] = $ this-> $ field ;
}
}
return $ properties;

保护函数clean_properties(){
global $ database;
$ clean_properties = array();
foreach($ this-> properties()as $ key => $ value){
$ clean_properties [$ key] = $ database-> escape_string($ value);
}
返回$ clean_properties;

public function create(){
global $ database;
$ properties = $ this-> clean_properties();
$ sql =INSERT INTO.static :: $ db_table。(。implode(,,array_keys($ properties))。);
$ sql。=VALUES('。implode(',',array_values($ properties))。');
if($ database-> query($ sql)){
$ this-> id = $ database-> last_id();
print_r($ sql);
var_dump($ sql);
返回true;
} else {
return false;
}
}
}
?>

print_r 显示以下结果:
$ b $ pre $ INSERT INTO图像(id,image_url,property_id,date)VALUES('','',' '1','2017-10-20 20:24:05')

< code $> var_dump 正在显示以下内容:

$ p $ string(89) 插入图像(id,image_url,property_id,date)VALUES('','','1','2017-10-20 20:24:05')

此外,这里是 HTML 页面:

 <?php include_onceadmin / head.php; ?> 
<?php if(!$ session-> is_signed_in()){redirect(../ index);}?>
<?php
if(isset($ _ POST ['submit'])){
$ images = new Images();
$ images-> new_images();
}
?>
< div class =container>
< div class =row>
< div class =col-xs-12 col-sm-6>
< form class =form-horizo​​ntalaction =method =postenctype =multipart / form-data>
< div class =form-group>
< label for =imagesclass =control-label>图片< / label>
< input type =fileclass =form-controlname =images []id =imagesmultiple =>
< / div>
< input type =submitname =submitvalue =Submitclass =btn btn-primary>
< / form>
< / div>
< / div>
< / div>
<?php includeadmin / footer.php; ?>


解决方案 ['images'] 是错误的。每个元素都不是单个文件的所有属性。每个元素是一个不同的属性,其中包含所有上传的属性的数组。例如。 $ _ FILES ['images'] ['name'] 是所有名称的数组。所以你需要循环这些属性之一,然后获得其他属性的相应元素。

  foreach($ _FILES ['images'] ['name'] as $ index => $ name){
$ file = array('name'=> $ name,'tmp_name'=&$; _FILES ['images' ] [ 'tmp_name的值'] [$指数]);
$ this-> set_files($ file);
...
}


I am trying to build a method in PHP to upload multiple files into and insert the files names into a MySQL database.

I am trying to build this based on PHP OOP.

Multiple issues I am facing and I have been stucking with this for more than 2 weeks.

First: the method is only inserting 1 row into the database even if I selected multiple files in the form.

Second: the method is not getting the files name, so even if it inserts only 1 row, it inserts an empty row.

Here is the images class:

<?php
class Images extends Crud{
  protected static $db_table = "images";
  protected static $table_fields = array("id", "image_url", "property_id", "date");
  public $id;
  public $image_url;
  public $property_id;
  public $date;
  public $filename;
  public $tmp_path = array();
  public $upload_dir = "images";
  public $errors = array();
  public $upload_errors_array = array(
    UPLOAD_ERR_OK           => "There is no error.",
    UPLOAD_ERR_INI_SIZE     => "The file size exceeds the upload_max_filesize",
    UPLOAD_ERR_FORM_SIZE    => "The file upload exceeds the MAX_FILE_SIZE",
    UPLOAD_ERR_PARTIAL      => "The uploaded file was only partially uploaded",
    UPLOAD_ERR_NO_TMP_DIR   => "Missing a temporary folder",
    UPLOAD_ERR_CANT_WRITE   => "Failed to write file on desk",
    UPLOAD_ERR_EXTENSION    => "A PHP extension stopped the file upload"
  );

  public function image_path(){
    return $this->upload_dir.DS.$this->image_url;
  }

  public function set_files($file){
    if(empty($file) || !$file || !is_array($file)){
      $this->errors[] = "There was no file uploaded here";
      return false;
    }else{
        $this->image_url = $file['name'];
        $this->tmp_path = $file['tmp_name'];
      }
  }
  public function new_images(){
    foreach ($_FILES['images'] as $file) {
      $this->set_files($file);
      $this->property_id    = "1";
      $this->date           = date('Y-m-d H:i:s');
      $target_path = $this->upload_dir . DS . $this->image_url;
      move_uploaded_file($this->tmp_path, $target_path);
      if($this->create()){
        print_r($file);
        var_dump($file);
      return true;
      }
    }
  }
}
 ?>

print_r is showing the following:

Array ( [0] => download (1).jpg [1] => download (2).jpg [2] => download (3).jpg [3] => download.jpg )

and var_dump is showing the following:

array(4) { [0]=> string(16) "download (1).jpg" [1]=> string(16) "download (2).jpg" [2]=> string(16) "download (3).jpg" [3]=> string(12) "download.jpg" }

More details:

Here is the main class which the images class extends from:

<?php
class Crud{
  protected static $db_table;
  public static function find(){
    return static::find_query("SELECT * FROM " . static::$db_table . "");
  }
  public static function find_limit($limit){
    return static::find_query("SELECT * FROM " . static::$db_table . " LIMIT " . $limit. "");
  }
  public static function find_id($id){
    global $database;
    $the_result_array = static::find_query("SELECT * FROM " . static::$db_table . " WHERE id='$id'");
    return !empty($the_result_array) ? array_shift($the_result_array) : false;
  }
  public static function find_query($sql){
    global $database;
    $set_result = $database->query($sql);
    $object_array = array();
    while($rows = mysqli_fetch_array($set_result)){
      $object_array[] = static::instantiation($rows);
    }
    return $object_array;
  }
  public static function instantiation($records){
    $calling_class = get_called_class();
    $object = new $calling_class;
    foreach ($records as $attribute => $value) {
      if($object->has_attribute($attribute)){
        $object->$attribute = $value;
      }
    }
    return $object;
  }
  private function has_attribute($attribute){
    $object_properties = get_object_vars($this);
    return array_key_exists($attribute, $object_properties);
  }
  protected function properties(){
    $properties = array();
    foreach (static::$table_fields as $field){
      if(property_exists($this, $field)){
        $properties[$field] = $this->$field;
      }
    }
    return $properties;
  }
  protected function clean_properties(){
    global $database;
    $clean_properties = array();
    foreach ($this->properties() as $key => $value) {
      $clean_properties[$key] = $database->escape_string($value);
    }
    return $clean_properties;
  }
  public function create(){
    global $database;
    $properties = $this->clean_properties();
    $sql = "INSERT INTO ".static::$db_table."(". implode(",", array_keys($properties)).")";
    $sql .= "VALUES ('". implode("','", array_values($properties)) ."')";
    if($database->query($sql)){
      $this->id = $database->last_id();
      print_r($sql);
      var_dump($sql);
      return true;
    }else{
      return false;
    }
  }
}
 ?>

print_r is showing the following result:

INSERT INTO images(id,image_url,property_id,date)VALUES ('','','1','2017-10-20 20:24:05')

var_dump is showing the follwoing:

string(89) "INSERT INTO images(id,image_url,property_id,date)VALUES ('','','1','2017-10-20 20:24:05')"

Furthermore, here is the HTML page:

<?php include_once "admin/head.php"; ?>
<?php if(!$session->is_signed_in()) {redirect("../index");}  ?>
<?php
 if(isset($_POST['submit'])){
   $images = new Images();
   $images->new_images();
 }
 ?>
<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-6">
      <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label for="images" class="control-label">نص الصورة البديل</label>
          <input type="file" class="form-control" name="images[]" id="images" multiple="">
        </div>
        <input type="submit" name="submit" value="Submit" class="btn btn-primary">
      </form>
    </div>
  </div>
</div>
<?php include "admin/footer.php"; ?>

解决方案

Your loop through $_FILES['images'] is wrong. Each element of this is not all the properties for a single file. Each element is a different property, which contains an array of those properties of all the uploads. E.g. $_FILES['images']['name'] is an array of all the names. So you need to loop through one of these properties, and then get the corresponding elements of the other properties.

foreach ($_FILES['images']['name'] as $index => $name) {
    $file = array('name' => $name, 'tmp_name' => $_FILES['images']['tmp_name'][$index]);
    $this->set_files($file);
    ...
}

这篇关于PHP OOP中的多文件上传方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆