上传PDF文件并将文件名发送到数据库

时间:2016-07-17 17:45:16

标签: php mysql file pdf upload

确定要提交一个包含文件输入和文本字段的小表单

在提交时,我希望它上传(仅限PDF文件)并将文件名发送到我的"资源"表

资源表如下所示:

id (AUTO_INC & Primary)
title (data from text field)
filename (from uploaded file, preferably with extension aswell)
dateadded (pulled from current date() )

这是我到目前为止的代码;

    <form enctype="multipart/form-data" action="<? echo $PHP_SELF ?>" method="post" id="myform" class="basic-form">
    <?php
    // IF FORM SUBMIT
    if (isset($_POST['submit']))
    {   
        $title    = $_POST['title'];
        $dateLog = date("y-m-d"); // DATE OF  ADDITION
        $timeLog = date("H:i:s", time() - 3600);   // TIME OF ADDITION 

// target directory & Extensions
$uploads_dir = '../resource_docs/';
$allowedExts = array("pdf", "doc");

//Loop file uploads
    foreach ($_FILES["upload"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES["upload"]["tmp_name"][$key];
            $name = $_FILES["upload"]["name"][$key];
            move_uploaded_file($tmp_name, "$uploads_dir/$name");
        }
    }

    // INSERT QUERY
    $sql="INSERT INTO resources (filename, title, dateadded)
          VALUES ('$name', '$title', '$dateLog')";

    $query = mysql_query($sql) or die("Cannot query the database.<br>" . mysql_error());

    }
    ?>

    <input type="file" name="upload" />
    <input name='title' type='text' value='' placeholder='Title Here'/>
    <input type="submit" name="submit" value="Upload"/>
    </form>

表单提交并将所有内容放在数据库中,文件名除外,它在浏览器底部显示其上传但目标目录中没有任何内容。

我错过了一些明显的东西 我可以让它只接受我的编码中的.pdf文件吗?

2 个答案:

答案 0 :(得分:1)

使用echo语句检查循环是否被执行。

示例:

foreach ($_FILES["upload"]["error"] as $key => $error) {
        echo "foreach working";
        if ($error == UPLOAD_ERR_OK) {
            echo "entering into if";
            $tmp_name = $_FILES["upload"]["tmp_name"][$key];
            $name = $_FILES["upload"]["name"][$key];
            move_uploaded_file($tmp_name, "$uploads_dir/$name");
        }
    }

答案 1 :(得分:0)

您的文件路径可能不存在或无效。