关于php:如何上传文件并将文件表存储到数据库中? | 珊瑚贝

How can I upload a file and store a file table into DB?


我正在使用 dropzone.js 和 Codeigniter 来处理带有文件上传过程的文章发布:

  • 有一个表格可以发表文章
  • 有一个dropzone允许用户上传文件
  • 用户提交文章前,可以上传文件。在这里,我需要一个数据库中的文件表来存储文章 ID 和文件名。

    我的问题是:
    只有在我点击提交表单按钮后,文章才会被存储到数据库中,然后我会得到文章 ID。但是,一旦我将文件拖到 dropzone 中,文件就会被上传。那么如何将”article_id – file_name”对存储到数据库中呢?

    这是我上传文件的代码:

    PHP 上传文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public function upload() {
        if (!empty($_FILES)) {
        $tempFile = $_FILES[‘file’][‘tmp_name’];
        $fileName = $_FILES[‘file’][‘name’];
        $targetPath = getcwd() . ‘/uploads/’;
        $targetFile = $targetPath . $fileName ;
        move_uploaded_file($tempFile, $targetFile);

        // store table in db
        $this->load->database(); // load database
        $this->db->insert(‘file_table’, array(‘id’=> , ‘article_id’ => , ‘file_name’ => $fileName, ‘created_time’=> date(“Y-m-d H:i:s”)));
        }
    }

    表单和dropzone的PHP:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <form>
               

       
           Drop files here or click to upload.<br />
           <span class=“note”>(You might select multiple files here.)</span>
       


    </form>

    • 您可以使用会话。上传文件时将文件ID设置为会话。当您保存文章时,从会话中获取文件ID并与文章ID一起保存。


    尝试使用 insert_id() 获取最后插入的 ID。

    • 非常感谢 MarlZ15199。我终于解决了这个问题,首先在文件 table = 0 中插入文章 ID,然后在我发布文章并使用 insert_id() 获取新 ID 后更新文章 ID。


    id 不是自动递增的吗?如果是这样,您不需要传递它,您可以传递 null 或跳过该字段。我在上面看到的 $fileName 变量中有文件名。

    • 嗨,天使,非常感谢您的回复。是的,它是自动增量。我将文章存储在一个表中,file_table 是另一个。但是在我提交文章表单并且在提交表单之前完成上传操作之前,我不会获得最新的文章 ID。


    来源:https://www.codenong.com/29493439/

    微信公众号
    手机浏览(小程序)

    Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

    Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

    Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8650.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
    0
    分享到:
    没有账号? 忘记密码?