上传和删除照片

时间:2018-01-17 20:17:21

标签: php sql

我有一个可以上传和删除照片的应用。现在我要么能够上传照片,要么我能够删除它。但出于某种原因,我无法做到这两点,这就是我的意思:

在下面的代码中,在Photograph类中,变量$ db_fields是照片数据库中列的数组。如果我将id字段从$ db_fields数组中删除,我可以上传照片。但我无法删除照片。如果我包含id字段,我可以删除照片,但现在我无法上传照片。

我需要在这做什么?如果您需要查看其他任何内容,请告诉我们。

谢谢, CM

photograph.php

<?php
require_once(LIB_PATH . DS . 'database.php');

class Photograph extends DatabaseObject {

    protected static $table_name = "photographs";
    protected static $db_fields = array('id','filename', 'type', 'size', 'caption');
    public $id;
    public $filename;
    public $type;
    public $size;
    public $caption;
    private $temp_path;
    protected $upload_dir = "images";
    public $errors = array();
    protected $upload_errors = array(
        UPLOAD_ERR_OK => "No errors.",
        UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
        UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
        UPLOAD_ERR_PARTIAL => "Partial upload.",
        UPLOAD_ERR_NO_FILE => "No file.",
        UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
        UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
        UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
    );


    public function attach_file($file) {

        if (!$file || empty($file) || !is_array($file)) {

            $this->errors[] = "No file was uploaded.";
            return false;
        } elseif ($file['error'] != 0) {

            $this->errors[] = $this->upload_errors[$file['error']];
            return false;
        } else {

            $this->temp_path = $file['tmp_name'];
            $this->filename = basename($file['name']);
            $this->type = $file['type'];
            $this->size = $file['size'];
            return true;
        }
    }

    public function save() {
        if (isset($this->id)) {
            $this->update();
        } else {
            if (!empty($this->errors)) {
                return false;
            }

            if (strlen($this->caption) > 255) {
                $this->errors[] = "The caption can only be 255 characters long.";
                return false;
            }


            if (empty($this->filename) || empty($this->temp_path)) {
                $this->errors[] = "The file location was not available.";
                return false;
            }


            $target_path = SITE_ROOT . DS . 'public' . DS . $this->upload_dir . DS . $this->filename;


            if (file_exists($target_path)) {
                $this->errors[] = "The file {$this->filename} already exists.";
                return false;
            }


            if (move_uploaded_file($this->temp_path, $target_path)) {
                if ($this->create()) {
                    unset($this->temp_path);
                    return true;
                }
            } else {
                $this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
                return false;
            }
        }
    }

    public function destroy() {
        if ($this->delete()) {
            $target_path = SITE_ROOT . DS . 'public' . DS . $this->image_path();
            return unlink($target_path) ? true : false;
        } else {
            return false;
        }
    }

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

    public function size_as_text() {
        if ($this->size < 1024) {
            return "{$this->size} bytes";
        } elseif ($this->size < 1048576) {
            $size_kb = round($this->size / 1024);
            return "{$size_kb} KB";
        } else {
            $size_mb = round($this->size / 1048576, 1);
            return "{$size_mb} MB";
        }
    }

    public function comments() {
        return Comment::find_comments_on($this->id);
    }

    public static function count_all() {
      global $database;
      $sql = "SELECT COUNT(*) FROM ".self::$table_name;
    $result_set = $database->query($sql);
      $row = $database->fetch_array($result_set);
    return array_shift($row);
    }

}

?>

database_object.php     

require_once(LIB_PATH . DS . 'database.php');

class DatabaseObject {

    private static $table_name;

    public static function find_all() {
        global $database;
        $query = "SELECT * FROM ".static::$table_name;
        return static::find_by_sql($query);
    }

    public static function find_by_id($id=0) {
        global $database;
        $query = "SELECT * FROM " . static::$table_name . " WHERE id =".$database->escape_value($id)." LIMIT 1";
        $result_array = static::find_by_sql($query);
        return !empty($result_array) ? array_shift($result_array) : false;
    }

    public static function find_by_sql($sql = "") {
        global $database;
        $result_set = $database->query($sql);
        $object_array = array();
        while ($row = $database->fetch_array($result_set)) {
            $object_array[] = static::instantiate($row);
        }
        return $object_array;
    }

    private static function instantiate($record) {
        $object = new static();
        foreach ($record as $attribute => $value) {
            if ($object->has_attribute($attribute)) {
                $object->$attribute = $value;
            }
        }
        return $object;
    }

    private function has_attribute($attribute) {
        $object_vars = $this->attributes();
        return array_key_exists($attribute, $object_vars);
    }

    protected function attributes() {
        $attributes = array();
        foreach (static::$db_fields as $field) {
            if (property_exists($this, $field)) {
                $attributes[$field] = $this->$field;
            }
        }
        return $attributes;
    }

    protected function sanitized_attributes() {
        global $database;
        $clean_attributes = array();
        foreach ($this->attributes() as $key => $value) {
            $clean_attributes[$key] = $database->escape_value($value);
        }
        return $clean_attributes;
    }

    public function save() {
        return isset($this->id) ? $this->update() : $this->create();
    }

    public function create() {
        global $database;
        $attributes = $this->attributes();
        $sql = "INSERT INTO ".static::$table_name." (";
        $sql .= join(", ", array_keys($attributes));
        $sql .= ") VALUES ('";
        $sql .= join("', '", array_values($attributes));
        $sql .= "')";
      if($database->query($sql)) {
        $this->id = $database->insert_id();
        return true;
      } else {
        return false;
      }
    }

    public function update() {
        global $database;
        $attributes = $this->sanitized_attributes();
        $attribute_pairs = array();
        foreach ($attributes as $key => $value) {
            $attribute_pairs[] = "{$key}='{$value}'";
        }
        $sql = "UPDATE " . static::$table_name . " SET ";
        $sql .= join(", ", $attribute_pairs);
        $sql .= " WHERE id=" . $database->escape_value($this->id);
        $database->query($sql);
        return ($database->affected_rows() == 1) ? true : false;
    }

    public function delete() {
        global $database;
        $sql = "DELETE FROM " . static::$table_name;
        $sql .= " WHERE id=" . $database->escape_value($this->id);
        $sql .= " LIMIT 1";
        $database->query($sql);
        return ($database->affected_rows() == 1) ? true : false;
    }
}
?>

photo_upload.php

<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) {
    redirect_to("login.php");
}
?>
<?php
$max_file_size = 10485760;   // expressed in bytes
//     10240 =  10 KB
//    102400 = 100 KB
//   1048576 =   1 MB
//  10485760 =  10 MB
//2e+6
$message="";
if (isset($_POST['submit'])) {
    $photo = new Photograph();
    $photo->caption = $_POST['caption'];
    $photo->attach_file($_FILES['file_upload']);
    if ($photo->save()) {
        // Success
        $session->message("Photograph uploaded successfully.");
        redirect_to('list_photos.php');
    } else {
        // Failure
        $message = join("<br />", $photo->errors);
    }
}
?>

<?php include_layout_template('admin_header.php'); ?>

<h2>Photo Upload</h2>

<?php echo output_message($message); ?>
<form action="photo_upload.php" enctype="multipart/form-data" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p><input type="file" name="file_upload" /></p>
    <p style="font-color:#000;">Caption: <input type="text" name="caption" value="" /></p>
    <input type="submit" name="submit" value="Upload" />
</form>


<?php include_layout_template('admin_footer.php'); ?>

来自&#39; database_object.php&#39;

public function create() {
        global $database;
        $attributes = $this->attributes();
        $sql = "INSERT INTO ".static::$table_name." (";
        $sql .= join(", ", array_keys($attributes));
        $sql .= ") VALUES ('";
        $sql .= join("', '", array_values($attributes));
        $sql .= "')";
      if($database->query($sql)) {
        $this->id = $database->insert_id();
        return true;
      } else {
        return false;
      }
    }

1 个答案:

答案 0 :(得分:0)

临时解决方案的摘要,因此您可以完成此问题。

create的方法中,您将使用$attributes = $this->attributes();获取所有属性(字段),然后使用数组键和值生成SQL语句。

这还包括id字段。

然后问题是尝试执行INSERT操作并包含id字段(它似乎是auto_increment唯一索引字段)。这对创建造成了很大的问题。

一个临时解决方案是,在$attributes完成此操作之后使用unset($attributes['id']);从您用于构建查询的$attributes = $this->attributes();中删除该字段,但它不漂亮且可以开发以后在闲暇时更好。

我希望我能帮助,并且快乐编码;)