-1

I need to update a PDF file that already has been uploaded for a certain user (using html form). I have added a code to update the PDF document (to choose another/new document) but it is not working. It is just updating the name of the file to the database without uploading the file to the folder and the path to the database like I have in my insert.php.

This is my insert.php code:

<?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "employees";

// Create connection
$conn = mysqli_connect($server, $user, $pass, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$dob = mysqli_real_escape_string($conn, $_POST['dob']);
$embg = mysqli_real_escape_string($conn, $_POST['embg']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$workplace = mysqli_real_escape_string($conn, $_POST['workplace']);
$workposition = mysqli_real_escape_string($conn, $_POST['workposition']);
$jobstartdate = mysqli_real_escape_string($conn, $_POST['jobstartdate']);
$contractfrom = mysqli_real_escape_string($conn, $_POST['contractfrom']);
$contractto = mysqli_real_escape_string($conn, $_POST['contractto']);
$healthbookfrom = mysqli_real_escape_string($conn, $_POST['healthbookfrom']);
$healthbookto = mysqli_real_escape_string($conn, $_POST['healthbookto']);
$bankaccount = mysqli_real_escape_string($conn, $_POST['bankaccount']);
$bank = mysqli_real_escape_string($conn, $_POST['bank']);
$workcode = mysqli_real_escape_string($conn, $_POST['workcode']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$bloodtype = mysqli_real_escape_string($conn, $_POST['bloodtype']);
$notes = mysqli_real_escape_string($conn, $_POST['notes']);
$contract_file = basename($_FILES['contractupload']['name']);
$contract_path = "files/contracts/$contract_file";
$contract_file = mysqli_real_escape_string($conn, $contract_file);

copy($_FILES['contractupload']['tmp_name'], $contract_path);  // copy the file to the folder


$sql = "INSERT INTO addemployees (fname, lname, dob, embg, address, city, mobile, email, workplace, workposition, jobstartdate, contractfrom, contractto, healthbookfrom,
                                  healthbookto, contractupload, bankaccount, bank, workcode, gender, bloodtype, notes)
        VALUES ('$fname', '$lname', '$dob', '$embg', '$address', '$city', '$mobile', '$email', '$workplace', '$workposition', '$jobstartdate', '$contractfrom', '$contractto',
                '$healthbookfrom', '$healthbookto', '$contract_file', '$bankaccount', '$bank', '$workcode', '$gender', '$bloodtype', '$notes')";

if (mysqli_query($conn, $sql)) {
  header("location: employees.php");
    // echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}


// Use this to write text for the connection ---> echo "Connected successfully";

//Close the connection
mysqli_close($conn);    
?>

This is my update.php code:

       <?php

// Include config file
require_once "new_db_connect.php";

if($_POST) {
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $embg = $_POST['embg'];
    $contractupload = $_POST['contractupload'];
    $contract_file = $_FILES['contractupload']['name'];
    $contract_path = "files/contracts/$contract_file";

copy($_FILES['contractupload']['tmp_name'], $contract_path);

    $id = $_POST['id'];

// UPDATE the info
    $sql = "UPDATE addemployees SET fname = '$fname', lname = '$lname', embg = '$embg', contractupload = '$contractupload' WHERE id = {$id}";
    if($connect->query($sql) === TRUE) {
        header("location: employees.php");

    } else {
        echo "Erorr while updating record : ". $connect->error;
    }

    $connect->close();

}

?>

And this is my edit.php code:

<?php

// Include config file
require_once "new_db_connect.php";

if($_GET['id']) {
    $id = $_GET['id'];

    $sql = "SELECT * FROM addemployees WHERE id = {$id}";
    $result = $connect->query($sql);

    $data = $result->fetch_assoc();

    $connect->close();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update Record</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <style type="text/css">
        .wrapper{
            width: 500px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="page-header">
                        <h2>Update User Info</h2>
                    </div>
                    <form action="update.php" method="post">

                      <div class="form-group">
                          <label>Name</label>
                          <input type="text" id="fname" name="fname" class="form-control" value="<?php echo $data['fname'] ?>">
                      </div>

                      <div class="form-group">
                          <label>Last Name</label>
                          <input type="text" id="lname" name="lname" class="form-control" value="<?php echo $data['lname'] ?>">
                      </div>

                      <div class="form-group">
                          <label>ID Number</label>
                          <input type="text" id="embg" name="embg" class="form-control" value="<?php echo $data['embg'] ?>">
                      </div>

                      <div class="form-group">
                          <label>Contract PDF</label>
                          <input type="file" name="contractupload" id="contractupload" class="form-control" style="border: 1px solid #CED4DA!important;" style="width: 50%!important;" value="<?php echo $data['contractupload'] ?>">
                      </div>

                      <input type="hidden" name="id" value="<?php echo $data['id'] ?>"/>
                      <input type="submit" class="btn btn-primary" value="Submit">
                      <a href="employees.php" class="btn btn-default">Cancel</a>
                  </form>

                </div>
            </div>
        </div>
    </div>
</body>
</html>

<?php
}
?>

Update

I have updated my code so it can be more readable and more simple. I am looking for help with updating the PDF file.

halfer
  • 19,824
  • 17
  • 99
  • 186
Blagojce
  • 27
  • 1
  • 9
  • 3
    Your code is huge and I'm guessing that it's not designed to be reproducible. You might wanna check SO's guide on [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Nino Filiu Dec 23 '18 at 00:41
  • @NinoFiliu I have updated my code so it can be more readable and more simple. I hope someone of you guys can be able to help me now, with updating the PDF file. Thanks – Blagojce Dec 23 '18 at 18:26
  • @Blagojce god job! But I suggest you to go even further and cut those lines with `mysqli_real_escape_string` to only those needed to reproduce the issue. What's more important, please describe which .php you use for uploading, which one you use for updating and why you show 3 php files, not 2? – YakovL Dec 23 '18 at 18:28
  • @YakovL i'm using **insert.php** for inserting the info to the database. **update.php** and **edit.php** for editing the already insert info of the user. I have 2 php files (update and edit) because it's easier to me to have them separated so the code can be more clean and more readable :-) Regarding the `mysqli_real_escape_string` lines, that is the complete info i'm inserting to the database and that is the same i use for edit (i have deleted the other code for here so it can be more readable) – Blagojce Dec 23 '18 at 18:30
  • @Blagojce so what are you trying to update? The pdf binary in DB or its metadata in DB? How do you fill your form, what you expect to happen and what actually happens? What the entry corresponding to the uploaded pdf looks like in DB before and after your edit? (skip the binary). You see, if you show the both states of the entry, showing insert.php is no longer relevant to the question – YakovL Dec 23 '18 at 18:42
  • This is the case. I'm working on an app for Employees Management. With insert.php i'm adding new employees and there i'm adding the employee work contract. I need the update so i can add new PDF file ( new contract ) when the old one expires ( it expires every 3 months and new needs to be added ). And this is where the issue starts :-) I can't figure it out how to add a new PDF file that will overwrite the old one. I hope it's more clear now. Thanks a lot @YakovL – Blagojce Dec 23 '18 at 18:48
  • Ok, if you need to change the pdf, here's the next step to narrow down the problem: check whether you upload the file successfully. If so, remove all the stuff with regard to uploading from your post, show the scheme of your DB and try if the code from update.php works with a manually uploaded file. Hopefully, you have a problem with either uploading the file or updating the DB, not both. – YakovL Dec 23 '18 at 18:57
  • I think my issue is with the code in **update.php** in the lines of `$contractupload = $_POST['contractupload']; $contract_file = $_FILES['contractupload']['name']; $contract_path = "files/contracts/$contract_file"; copy($_FILES['contractupload']['tmp_name'], $contract_path);` In my employees.php (where i list all of the employees in html table) it shows just the name of the pdf file like it is uploaded. But it is not moving it to the folder and the file is not accessible. – Blagojce Dec 23 '18 at 19:03
  • This is the error i'm getting in php log file: `[23-Dec-2018 19:00:26 UTC] PHP Notice: Undefined index: contractupload in C:\wamp64\www\management3\update.php on line 11 [23-Dec-2018 19:00:26 UTC] PHP Stack trace: [23-Dec-2018 19:00:26 UTC] PHP 1. {main}() C:\wamp64\www\management3\update.php:0 [23-Dec-2018 19:00:26 UTC] PHP Notice: Undefined index: contractupload in C:\wamp64\www\management3\update.php on line 14 [23-Dec-2018 19:00:26 UTC] PHP Stack trace: [23-Dec-2018 19:00:26 UTC] PHP 1. {main}() C:\wamp64\www\management3\update.php:0` – Blagojce Dec 23 '18 at 19:05
  • `[23-Dec-2018 19:00:26 UTC] PHP Warning: copy(): Filename cannot be empty in C:\wamp64\www\management3\update.php on line 14 [23-Dec-2018 19:00:26 UTC] PHP Stack trace: [23-Dec-2018 19:00:26 UTC] PHP 1. {main}() C:\wamp64\www\management3\update.php:0 [23-Dec-2018 19:00:26 UTC] PHP 2. copy() C:\wamp64\www\management3\update.php:14` – Blagojce Dec 23 '18 at 19:06
  • 1
    File inputs are only put into `$_FILES`, not `$_POST`. So `$contractupload = $_POST['contractupload'];` is obviously wrong. – Barmar Dec 23 '18 at 20:53
  • 1
    Why do you still refuse to use `move_uploaded_file()`? This was mentioned in response to your first question about the upload script. – Barmar Dec 23 '18 at 20:55
  • @Barmar first thanks a lot for showing/helping me :-). I'm not refusing to use move_uploaded_file, it didnt work when i try: i replaced `copy($_FILES['contractupload']['tmp_name'], $contract_path);` with `move_uploaded_file($_FILES['contract_file']['tmp_name'], $contract_path);` and it didn't moved the file :( – Blagojce Dec 23 '18 at 21:35
  • On the other, i replaced `$contractupload = $_POST['contractupload'];` with `$contractupload = $_FILES['contractupload'];` and it throws errors :-( – Blagojce Dec 23 '18 at 21:36
  • 1
    @Blagojce It's `$_FILES['contractupload']['tmp_name']`. – Barmar Dec 24 '18 at 15:06

1 Answers1

1

$_POST['contractupload'] won't work. The filename is only in $_FILES. You should process it the same way you do in insert.php.

I've also shown how to rewrite your code using a prepared statement instead of variable substitution.

And you should use move_uploaded_file() instead of copy(). See Difference between copy and move_uploaded_file.

<?php

// Include config file
require_once "new_db_connect.php";

if($_POST) {
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $embg = $_POST['embg'];
    $contract_file = basename($_FILES['contractupload']['name']);
    $contract_path = "files/contracts/$contract_file";

    move_uploaded_file($_FILES['contractupload']['tmp_name'], $contract_path);

    $id = $_POST['id'];

    // UPDATE the info
    $stmt = $connect->prepare("UPDATE addemployees SET fname = ?, lname = ?, embg = ?, contractupload = ? WHERE id = ?");
    $stmt->bind_param("ssssi", $fname, $lname, $embg, $contract_file, $id);
    if($stmt->execute()) {
        header("location: employees.php");
    } else {
        echo "Erorr while updating record : ". $stmt->error;
    }

    $connect->close();

}

?>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you very much. I replaced your code with mine, but it still doesn't work. It doesn't show any error in the browser but i see some errors in php log file: – Blagojce Dec 23 '18 at 21:42
  • `[23-Dec-2018 21:41:32 UTC] PHP Notice: Undefined index: contractupload in C:\wamp64\www\management3\update.php on line 10 [23-Dec-2018 21:41:32 UTC] PHP Stack trace: [23-Dec-2018 21:41:32 UTC] PHP 1. {main}() C:\wamp64\www\management3\update.php:0 [23-Dec-2018 21:41:32 UTC] PHP Notice: Undefined index: contractupload in C:\wamp64\www\management3\update.php on line 13 [23-Dec-2018 21:41:32 UTC] PHP Stack trace: [23-Dec-2018 21:41:32 UTC] PHP 1. {main}() C:\wamp64\www\management3\update.php:0` – Blagojce Dec 23 '18 at 21:42
  • It doesn't move the file to the folder, and it doesn't show the name of the file in DB or in the table where i list all of the users. – Blagojce Dec 23 '18 at 21:49
  • 1
    BTW, you can't set the default value of a `type="file"` input. See https://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html – Barmar Dec 24 '18 at 15:09
  • the `print_r($_FILES);` shows error and says Array() [Error](https://i.imgur.com/gNJlyPu.png) – Blagojce Dec 24 '18 at 15:41
  • thanks for pointing for the file type. I had forgotten to add `enctype="multipart/form-data"` :-) When i try it with `move_uploaded_file` it didn't work, and when i try it with `copy` it did work. There is something wrong with `move`. Can you please help with it? I was using `move_uploaded_file($_FILES['contractupload']['tmp_name'], $contract_path);` Thanks a lot. – Blagojce Dec 24 '18 at 15:48
  • I can't think of a reason why `copy` would work but `move_uploaded_file` doesn't. Did you get an error from it? – Barmar Dec 24 '18 at 18:20
  • Barmar, no there is no new error showing in the log file – Blagojce Dec 25 '18 at 16:33
  • 1
    Then I can't think of a reason it wouldn't work. `move_uploaded_file` does the same thing as `copy`, except that it checks that the file is actually in the upload directory, and it deletes it afterwards. Do you have `error_reporting(E_ALL);` enabled so that all warnings are logged? – Barmar Dec 25 '18 at 21:19
  • i don't know what happened but i tried `move_uploaded_file` again and it just works now. Weird, because i have comment that line and was using `copy` instead. Now i just uncomment the line and it just works :) Thank you very much for all of your help. – Blagojce Dec 26 '18 at 08:09