简体   繁体   中英

Upload file name to SQL via PHP

I am really stuck on this problem. I have spent the better half of two days try to figure out what is wrong researching other method, but nothing is working for me.

My issue here, is i can't get the form to save the file name(attachment_file) into the SQL database. I can get all other information stored in there and i can also get the file to move to another folder, but it just won't save the file name for me.

Can someone please take a look at this for me please or point me in the correct direction

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"]
        )
    );
}
}

?>

You can't get the file name from $_POST. It's in $_FILES. Use this for the filename

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

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

Use this:

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

  • Keep your file name small. eg: abc.jpg , xyz.png

Code have few bugs or need improvements in insert.php

Check post

Check, if this is POST by request method

$_SERVER['REQUEST_METHOD'] == 'POST'

Integrity

If your file, need to be with all POST data, then process them in two separate, independent IF block is not good idea.

One of you problems, is that first you check if everything is correct with file, and move this with correct name, then check rest of POST data.

As you don't check

  • What you do, when $_FILES['attachment_file']['error'] != 0 ? Nothing and still try to save filename.
  • What you do, when move_uploaded_file return false ? didn't move file due some problems? Nothing and still try to save filename.
  • What if you file file is to big? Nothing and still try to save filename.

This indicate to errors or hidden bugs.

You should get you file name from:

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

not from:

$_POST["attachment_file"]

This returning null . You use this at Add and Edit part of you file.

filename

If you have in Database:

`attachment_file` varchar(100) DEFAULT NULL,

Then remember, to validate if filename have correct length to 100 chars.

Last advice

If you don't have alternative scenario for if(isset($_POST['operation'])) then why to create some big IF block. For example, you can check this with negation as start:

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

I hope, to show you problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM