NavyPixel
NavyPixel

Reputation: 260

upload PDF file and send filename to database

OK tying to submit a small form, with an file input and a textfield

on submit i want it to upload the (PDF FILES ONLY) and send the filename to my "resources" table.

Resources table looks like this:

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

here is the code i have so far;

    <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>

The form submits and puts everything in database except the filename and it shows at bottom of browser that its uploading but nothing in my target directory.

did i miss something obvious and can i get it to only accept .pdf files from my coding?

Upvotes: 0

Views: 2178

Answers (2)

Kalaivanan
Kalaivanan

Reputation: 519

Use echo statement to check whether the loop is executed or not.

Example:

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

Upvotes: 1

Kalaivanan
Kalaivanan

Reputation: 519

Your File Path may not be existed or invalid.

Upvotes: 0

Related Questions