通过PHP将文件名上传到SQL

时间:2017-05-19 06:30:33

标签: php mysql ajax file-upload

我真的坚持这个问题。我花了两天半的时间试着找出研究其他方法的错误,但没有什么对我有用。

我的问题是,我无法获取将文件名(attachment_file)保存到SQL数据库中的表单。我可以获取存储在那里的所有其他信息,我也可以将文件移动到另一个文件夹,但它不会为我保存文件名。

有人可以请我帮我看看,或指出我正确的方向

db.sql

-- Database: `collective_crm`
--

-- --------------------------------------------------------

--
-- Table structure for table `page__recruit`
--

CREATE TABLE `page__recruit` (
`recruitment_id` int(11) NOT NULL,
`first_name` varchar(30) DEFAULT NULL,
`last_name` varchar(30) DEFAULT NULL,
`contact_number` varchar(100) DEFAULT NULL,
`email_address` varchar(100) DEFAULT NULL,
`attachment_file` varchar(100) DEFAULT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `page__recruit`
--
ALTER TABLE `page__recruit`
ADD PRIMARY KEY (`recruitment_id`);

-- AUTO_INCREMENT for table `page__recruit`
--
ALTER TABLE `page__recruit`
MODIFY `recruitment_id` int(11) NOT NULL AUTO_INCREMENT;

index.php - html / datatable

<html>
<head>
    <title>Recruitment - CollectiveCRM</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>       
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

    <style>
        ::-webkit-scrollbar { display: none; }
        body { margin:0; padding:0; background-color:#f1f1f1; }
        .box { margin-left:50px; width:97.5%; padding:15px; background-color:#fff; border:1px solid #ccc; }
        .position { width:100%; border-radius:0px; border:0px; border-bottom:1px solid rgba(0,0,0,0.30); }
        input, input:focus, select, select:focus, textarea, textarea:focus { outline:none !important; box-shadow:none !important; }
        table { width:100%; }
        .btn-style { width:100px; }
        h4 { color:#2092DF; }
        #clientsModal table { margin-left:3%; }
        #clientsModal table input { width:288px; height:30px; border:none; border-bottom:1px solid green; border-radius:0px; }
        #clientsModal table select { width:288px; height:30px; border:none; border-bottom:1px solid green; border-radius:0px; }
        #clientsModal table textarea { width:660px; border:none; border-bottom:1px solid green; border-radius:0px; }
        #clientsModal table input:focus { outline:none; }
        #clientsModal table select:focus { outline:none; }
        #clientsModal table textarea:focus { outline:none; }
        #clientsModal table td { padding-left:10px; padding-bottom:10px; }
        .btn-custom { margin-left:50px; margin-top:5px; height:40px; background-color:transparent; border:none; border-right:1px solid silver; font-size:20px; color:silver; }
        .btn-custom:hover { font-size:20px; color:skyblue; }
        .btn-custom:focus { outline:none; font-size:20px; color:skyblue; }
        .btn-custom .addnewclient { display:none; }
        .btn-custom:hover .addnewsymbol { display:none; }
        .btn-custom:hover .addnewclient { display:inline; }
        .btn-logout { border-radius:20px; height:40px; width:40px; margin-top:5px; background-color:transparent; border:1px solid silver; }
        .btn-logout:hover { border:1px solid red; }
        .modal-content { border-radius: 0; border: none; }
        .modal-header { border-bottom-color: #EEEEEE; background-color: #FAFAFA; }
        .modal.right.fade .modal-dialog { right: -320px; -webkit-transition: opacity 0.3s linear, right 0.3s ease-out; -moz-transition: opacity 0.3s linear, right 0.3s ease-out; -o-transition: opacity 0.3s linear, right 0.3s ease-out; transition: opacity 0.3s linear, right 0.3s ease-out; }
        .modal.right.fade.in .modal-dialog { right: 0; }
        .modal.right .modal-body { padding: 15px 15px 80px; }
        .modal.right .modal-content { height: 100%; overflow-y: auto; }
        .modal.right .modal-dialog { position: fixed; margin: auto; width: 750px; height: 100%; -webkit-transform: translate3d(0%, 0, 0); -ms-transform: translate3d(0%, 0, 0); -o-transform: translate3d(0%, 0, 0); transform: translate3d(0%, 0, 0); }
        .logout { color:rgba(255,0,4,0.60); }
        .logout:hover { color:rgba(255,0,4,1.00); }
    </style>
</head>
<body>
    <?php include('navbar.php') ?>

    <div id="top-menu" style="width:100%; height:50px; background-color:white;">

        <button id="client_add_button" class="btn-custom" data-toggle="modal" data-target="#clientsModal"><span class="addnewsymbol">&nbsp;<span class="glyphicon glyphicon-plus"></span>&nbsp;</span><span class="addnewclient">Add New</span></button>

        <div class="dropdown" style=" margin-left:97%; margin-top:-45px;">
            <a class="logout" href="functions/logout.php">
                <button class="btn-logout dropdown-toggle glyphicon glyphicon-off" type="button" id="acountdetails" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"></button>
            </a>
        </div>
    </div>

index.php - datatable

<div class="container box">
        <div class="table-responsive">
            <table id="data" class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th width="18.5%">First Name</th>
                        <th width="18.5%">Last Name</th>
                        <th width="15%">Contact Number</th>
                        <th width="20%">Email Address</th>
                        <th width="15%">Resume</th>
                        <th width="5%"></th>
                        <th width="5%"></th>
                        <th width="5%"></th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>

index.php - modal

<div id="clientsModal" class="modal right in fade">
<div class="modal-dialog modal-lg">
    <form method="post" id="clients_form" enctype="multipart/form-data">
        <div class="modal-content">
            <div class="modal-body">
                <table>
                    <tr>
                        <td>
                            <label>First Name</label>
                            <input id="first_name" name="first_name" type="text" class="form-control">
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label>Last Name</label>
                            <input id="last_name" name="last_name" type="text" class="form-control">
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label>Contact Number</label>
                            <input id="contact_number" name="contact_number" type="tel" class="form-control">
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label>Email Address</label>
                            <input id="email_address" name="email_address" type="email" class="form-control">
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label>Resume</label>
                            <input id="attachment_file" name="attachment_file" type="file" class="form-control">
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>                        
                            <input type="hidden" name="recruitment_id" id="recruitment_id" />
                            <input type="hidden" name="operation" id="operation" />
                            <input style="width:100px; height:34px; border-radius:5px;" ng-click="uploadFile()" type="submit" name="action" id="action" class="btn btn-style btn-success" value="Add" />
                            <button type="button" class="btn btn-style btn-danger" data-dismiss="modal">Close</button>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </form>
</div>

index.php - script

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    $('#client_add_button').click(function(){
        $('#clients_form')[0].reset();
        $('#action').val("Add");
        $('#operation').val("Add");
    });

    var dataTable = $('#data').DataTable({
        "processing":true,
        "serverSide":true,
        "order":[],
        "ajax":{
            url:"functions/recruitment/fetch.php",
            type:"POST"
        },
        "pageLength": 100,
        "columnDefs":[
            {
                "targets":[0, 1, 2, 3, 4, 5, 6, 7],
                "orderable":false,
            },
        ],

    });

    $(document).on('submit', '#clients_form', function(event){
        event.preventDefault();

        if(first_name != '')
        {
            $.ajax({
                url:"functions/recruitment/insert.php",
                method:'POST',
                data:new FormData(this),
                contentType:false,
                processData:false,
                success:function(data)
                {
                    $('#clients_form')[0].reset();
                    $('#clientsModal').modal('hide');
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            alert("Please Fill In All Required Fields");
        }
    });

    $(document).on('click', '.update', function(){
        var recruitment_id = $(this).attr("id");
        $.ajax({
            url:"functions/recruitment/fetch_single.php",
            method:"POST",
            data:{recruitment_id:recruitment_id},
            dataType:"json",
            success:function(data)
            {
                $('#clientsModal').modal('show');
                $('#first_name').val(data.first_name);
                $('#last_name').val(data.last_name);
                $('#contact_number').val(data.contact_number);
                $('#email_address').val(data.email_address);
                $('#attachment_file').val(data.attachment_file);
                $('#recruitment_id').val(recruitment_id);
                $('#action').val("Save");
                $('#operation').val("Edit");
            }
        })
    });

    $(document).on('click', '.delete', function(){
        var recruitment_id = $(this).attr("id");
        if(confirm("Are you sure you want to delete this?"))
        {
            $.ajax({
                url:"functions/recruitment/delete.php",
                method:"POST",
                data:{recruitment_id:recruitment_id},
                success:function(data)
                {
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            return false;   
        }
    });


});
</script>

insert.php

<?php
include('../db.php');
include('function.php');
if(isset($_POST["operation"]))
{

if(isset($_FILES['attachment_file']))
        {
            $file = $_FILES['attachment_file'];
            // print_r($file);

            $file_name = $file['name'];
            $file_tmp = $file['tmp_name'];
            $file_size = $file['size'];
            $file_error = $file['error'];

            $file_ext = explode('.', $file_name);
            $file_ext = strtolower(end($file_ext));
            // print_r($file_ext);

            $allowed = array('pdf', "txt", 'xlsx');

            if(in_array($file_ext, $allowed))
                {
                    if($file_error === 0)
                        {
                            if($file_size <= 2000000)
                                {
                                    $file_name_new = uniqid('', true) . '.' . $file_ext;
                                    // echo $file_name_new = uniqid('', true) . '.' . $file_ext;
                                    $file_destination = '../../upload/' . $file_name;
                                    // echo $file_destination = '../../upload/' . $file_name_new;

                                    if(move_uploaded_file($file_tmp, $file_destination))
                                        {
                                        }
                                }
                        }
                }
        };

if($_POST["operation"] == "Add")
{
    $statement = $connection->prepare("
        INSERT INTO page__recruit (
        first_name,
        last_name,
        contact_number,
        email_address,
        attachment_file
        ) 
        VALUES (
        :first_name,
        :last_name,
        :contact_number,
        :email_address,
        :attachment_file
        )
    ");
    $result = $statement->execute(
        array(
            ':first_name' => $_POST["first_name"],
            ':last_name' => $_POST["last_name"],
            ':contact_number' => $_POST["contact_number"],
            ':email_address' => $_POST["email_address"],
            ':attachment_file' => $_POST["attachment_file"],
        )
    );
}
if($_POST["operation"] == "Edit")
{
    $statement = $connection->prepare(
        "UPDATE page__recruit
        SET
        first_name = :first_name,
        last_name = :last_name,
        contact_number = :contact_number,
        email_address = :email_address,
        attachment_file = :attachment_file

        WHERE recruitment_id = :recruitment_id
        "
    );
    $result = $statement->execute(
        array(

            ':first_name' => $_POST["first_name"],
            ':last_name' => $_POST["last_name"],
            ':contact_number' => $_POST["contact_number"],
            ':email_address' => $_POST["email_address"],
            ':attachment_file' => $_POST["attachment_file"],
            ':recruitment_id' => $_POST["recruitment_id"]
        )
    );
}
}

?>

3 个答案:

答案 0 :(得分:0)

您无法从$ _POST获取文件名。它在$ _FILES中。用于文件名

$_FILES['attachment_file']['name']

参考:http://php.net/manual/en/features.file-upload.post-method.php

答案 1 :(得分:0)

使用此:

  • $filename = basename($_FILES['attachment_file']['name']);

  • 保持文件名小。例如:abc.jpgxyz.png

答案 2 :(得分:0)

代码在insert.php

中几乎没有错误或需要改进

检查帖子

检查,如果这是按请求方法POST

  

$ _ SERVER ['REQUEST_METHOD'] =='POST'

完整性

如果您的文件需要包含所有POST数据,那么在两个独立的IF块中处理它们并不是一个好主意。

您遇到的一个问题是,首先检查文件是否一切正确,然后使用正确的名称移动它,然后检查其余的POST数据。

因为你没有检查

  • 你做什么,$_FILES['attachment_file']['error'] != 0?没什么,仍然试图保存文件名。
  • move_uploaded_file返回false时你做了什么?由于一些问题,没有移动文件?没什么,仍然试图保存文件名。
  • 如果你提交文件很重要怎么办?没什么,仍然试图保存文件名。

这表示错误或隐藏的错误。

您应该从以下网址获取文件名:

$_FILES['attachment_file']['name']

不是来自:

$_POST["attachment_file"]

此返回null。您可以在文件的AddEdit部分使用此功能。

的文件名

如果你有数据库:

`attachment_file` varchar(100) DEFAULT NULL,

然后记住,验证文件名是否具有100个字符的正确长度。

最后的建议

如果您没有if(isset($_POST['operation']))的替代方案,那么为什么要创建一些大IF块。例如,您可以使用否定作为开始来检查:

if(!isset($_POST['operation'])) {
    die('Need to send correct POST operation.');
}

我希望,向你展示问题。