0

I have a full script of my php file. Its a dataTable with a browse button to add new videos toe the Database and reload it in the DataTable

The problem is that the entry in the database is made, but the file never gets copied from its original location to the library/video folder.

I have tried and tried toe get it going by it seems like the part of php move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path) is never executed or something.

<?php

include 'config.php';

$sTable = "media";


$rootFolder = '../video/';
$libraryFolder = '../video/library/';
$priorityFolder = '../video/priority/';

if (!is_dir($rootFolder)) {
    mkdir($rootFolder, 0777, true);
}
if (!is_dir($libraryFolder)) {
    mkdir($libraryFolder, 0777, true);
}
if (!is_dir($priorityFolder)) {
    mkdir($priorityFolder, 0777, true);
}



if(isset($_POST['script'])){


    try {
        $db = new PDO(
            "mysql:host=".Config::$DB_HOST.";dbname=".Config::$DB_DATABASE.";charset=utf8",
            Config::$DB_USERNAME,
            Config::$DB_PASSWORD
        );
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        print_r('CONNECTED TO DATABASE');
    } catch(PDOException $e) {
        print_r('ERROR CONNECTING TO DATABASE');
    }


    switch($_POST['script']){

        case 'fetchAll':
            $query = $db->prepare("SELECT * FROM $sTable");
            $query->execute();
            echo json_encode(array('media' => $query->fetch()));
            break;



        case 'insert':
            $target = $_POST['file'];
            $target_path = "../video/library/";
            $target_path = $target_path . $target;


            if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
                echo "The file ".  $target ." has been uploaded";

            } else{
                echo "There was an error uploading the file, please try again!";
            }


            $data = array(
                ':name' => $target,
                ':path' => $target_path);
            $table = 'media';
            $fields = array('name', 'path');
            $parameters = array(':name', ':path');
            $param = implode(',',$parameters);

            $stmt = $db->prepare("INSERT INTO {$table} (name, path) VALUES (:name, :path)");

            try {
                $db->beginTransaction();
                $stmt->execute(array("$parameters[0]" => $data[':name'], "$parameters[1]" => $data[':path']));
                $db->commit();
                print $db->lastInsertId();
            } catch(PDOExecption $e) {
                $db->rollback();
                print "Error!: " . $e->getMessage() . "</br>";
            }


            break;

        default:
            print_r('default');
            break;


    }
}


$db = null;










?>

<script>
    $(document).ready( function () {
        $('#vidlib_dtable').dataTable( {
            "dom": '<"top"f>rt<"bottom"lp><"clear">'
        } );
    } );
</script>




<script>
    $("#uploadedfile").on("change", function(){
        var file = this.files[0];
        var fileName = file.name;
        var fileSize = file.size;
        var fileType = file.type;
    });


    $(document).ready( function () {
        $("#vidUpdSubmit").click(function() {

            oFiles = document.getElementById("uploadedfile").files[0];
            nFiles = oFiles.name;
            nSize = oFiles.size;

            var myFile = $('#uploadedfile').prop("files")['name'];
            var url = "./inc/MediaScripts.php"; // the script where you handle the form input.

            $.ajax({
                type: "POST",
                data: ({'script':'insert',
                    'file': nFiles}
                    ),
                cache: false,
                success:function(data){
                    alert(data);
                },error:function(errormsg){
                    alert('EPPIC FAIL');
                }
            });

            return false; // avoid to execute the actual submit of the form.
        });
    } );
</script>





<div class="site_window_header">File manager</div>
<div>
    <div class="vl_buttonPane">
        <form  id="vidUpdForm" action="" method="POST">
            <input type="hidden" name="sctipt" value="insert" id="sctipt"/>
            Choose a file to upload: <input name="uploadedfile" id="uploadedfile" type="file" /><br />
            <input type="submit" id="vidUpdSubmit" value="Upload File" />
        </form>
    </div>
    <div class="vl_rightPane">

        <table id="vidlib_dtable" class="display">
            <thead>
            <tr>
                <th>Name</th>
                <th>Title</th>
                <th>File path</th>
                <th>Duration</th>
                <th>Date uploaded</th>
                <th>Uploaded by</th>
                <th>Key words</th>
                <th>Comments</th>
            </tr>
            </thead>
        </table>
    </div>
</div>

HERE is a link to a dropbox zip file with a manageable working copy of the program

SOLUTION: thanks to -> Alexander Ceballos

Upload Multiple Files with PHP and JQuery

Community
  • 1
  • 1
morne
  • 4,035
  • 9
  • 50
  • 96
  • So are you getting your error message "There was an error..."? – Patrick Q Jul 16 '14 at 13:59
  • @PatrickQ What error did you get? – morne Jul 16 '14 at 14:04
  • It's not my code. I'm not the one running it. You have two `echo` statements related to this part of your code. One of them should be executed. Which one are you seeing, the error or the success? – Patrick Q Jul 16 '14 at 14:07
  • @PatrickQ okay. I dont get anything, but it seems like the `move_uploaded_file($_FILES['uploadedfile']['tmp_name']` bit gives the problem. This is where the file should be copied from PHP's temp folder toe the target folder. But why is it not...? The entry in the DB is made. Just the copy thats the problem. Do you know more about `$_FILES` to maybe give me some insight? – morne Jul 16 '14 at 14:11
  • Please create an [MCVE](http://stackoverflow.com/help/mcve) – Patrick Q Jul 16 '14 at 14:21
  • @PatrickQ I have included a link to DropBox that contains a small project with sql DB to be able to have the same environment – morne Jul 16 '14 at 14:59
  • 1
    http://stackoverflow.com/questions/24168040/upload-multiple-files-with-php-and-jquery/24168617#24168617 – Alexander Ceballos Jul 16 '14 at 15:07
  • @Alexander Ceballos - Thanks for the answer [http://stackoverflow.com/questions/24168040 [1] [1]: http://stackoverflow.com/questions/24168040/upload-multiple-files-with-php-and-jquery/24168617#24168617 – morne Jul 17 '14 at 07:57

1 Answers1

3

So the problem isn't with $_FILES the problem is that you are not submitting the file. You are using ajax to post the file name(nfiles) and the value 'insert' with data:({'script':'insert', 'file':nfiles})which allows your script to process the the table update. However, you aren't actually posting the file since the form isn't being submitted, so $_FILES['uploadedfile] is actually undefined. You either need to actually submit the form and then you will be able to handle moving your file in the way your script is currently written. Or you need to add the file to your ajax post which will require you to create a form data object var formData = new FormData();. Check this page out for more on uploading files with ajax or have a look at this example. Hope this helps.

Community
  • 1
  • 1
light
  • 232
  • 2
  • 9