0

Can anyone help me on this. I've been working it about 3 days. This is about updating the records. When I update the data, all data's updated except for the the "file". The "file" became empty on the database.

Here is the code for;

EDIT/UPDATE FORM:

<label style="color:#e91e63">Attachement</label>
  <div class="input-group input-group-md">
        <span class="input-group-addon">
            <i class="material-icons">file_upload</i>
        </span>
        <div class="form-line">
            <input type="file" name="files" id="files" required>
        </div>
    </div>

  <!-- Edited Date -->

      <input type="hidden" name="id" id="id" />

  <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success waves-effect" />


<script>
$(document).ready(function(){
  $('#edit').click(function(){
    $('#insert').val("Insert");
    $('#insert_form')[0].reset();
  });

  $(document).on('click', '.edit_data', function(){
    var id = $(this).attr("id");
    var extension = $('#files').val().split('.').pop().toLowerCase();

    if(extension != '') {
      if(jQuery.inArray(extension, ['gif','png','jpg','jpeg', 'pdf']) == -1) {
        alert("Invalid File");
        $('#files').val('');
        return false;
      }
    }
      $.ajax({
      url:"script/fetch.php",
      method:"POST",
      data:{id:id},
      dataType:"json",
      success:function(data){
        $('#dated').val(data.dated);
        $('#ctrl_no').val(data.ctrl_no);
        $('#title').val(data.title);
        $('#category').val(data.category);
        $('#file').val(data.file);
        $('#fname').val(data.fname);
        $('#adate').val(data.adate);
        $('#createdby').val(data.createdby);
        $('#id').val(data.id);
        $('#insert').val("Update");
        $('#update_Modal').modal('show');
      }
    });
  });

  $('#insert_form').on("submit", function(event){
    event.preventDefault();
      $.ajax({
        url:"script/insert.php",
        method:"POST",
        data:$('#insert_form').serialize(),
        beforeSend:function(){
          $('#insert').val("Inserting");
        },
        success:function(data){
          $('#insert_form')[0].reset();
          $('#update_Modal').modal('hide');
          $('#refresh').html(data);
        }
      });
  });
});
</script>

Fetching the data from the database:

<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "record");
if(isset($_POST["id"]))
{
    $query = "SELECT * FROM dashboard WHERE id = '".$_POST["id"]."'";
    $result = mysqli_query($connect, $query);
    $row = mysqli_fetch_array($result);
    echo json_encode($row);
}
?>

Updating the data.

<?php
$connect = mysqli_connect("localhost", "root", "", "record");
if(!empty($_POST))
{
  $output = '';
  $message = '';

  $ctrl_no = mysqli_real_escape_string($connect, $_POST["ctrl_no"]);
  $title = mysqli_real_escape_string($connect, $_POST["title"]);
  $category = mysqli_real_escape_string($connect, $_POST["category"]);
  $fname = mysqli_real_escape_string($connect, $_POST["fname"]);
  $adate = mysqli_real_escape_string($connect, $_POST["adate"]);
  $createdby = mysqli_real_escape_string($connect, $_POST["createdby"]);

  //file upload

  $file = '';
  if($_FILES["files"]["name"] = '')
  {
    $file = upload_file();
  }
  else
  {
    $file = $_POST["file"];
  }

  if($_POST["id"] != '')
  {
    $query = "
    UPDATE `dashboard`
    SET
    `ctrl_no`='$ctrl_no',
    `title`='$title',
    `category`='$category',
    `file`='$file',
    `fname`='$fname',
    `adate` = '$adate',
    `createdby` = '$createdby'
    WHERE `id`='".$_POST["id"]."'";
    $message = 'Data Updated.';
  }

  if(mysqli_query($connect, $query))
  {
    $output .= "<div class='alert alert-success alert-dismissible'>
    <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
    <strong>Success!</strong> $message
    </div>";
    $select_query = "SELECT * FROM `dashboard` ORDER BY `id` DESC";
    $result = mysqli_query($connect, $select_query);
    $output .= '
    <table id="dataTable" style="width:100%" class="table table-bordered table-striped table-hover">
    <thead>
    <tr>
    <th width="6%"><b>Date</b></th>
    <th width="8%"><b>Control No.</b></th>
    <th width="37%"><b>Title / Particular</b></th>
    <th width="17%"><b>Category</b></th>
    <th width="10%"><b>From /<br />End-user</b></th>
    <th width="10%"><b>File</b></th>
    <th width="7%"><b>Action</b></th>
    </tr>
    </thead>
    <tbody>
    ';
    while($row = mysqli_fetch_array($result))
    {
      $output .= '';
    }
    $output .= '</tbody></table>';
  }
  echo $output;
}

function upload_file()
{
    if(isset($_FILES["files"]))
    {
        $extension = explode('.', $_FILES['files']['name']);
        $new_name = rand() . '.' . $extension[1];
        $destination = '../file/' . $new_name;
        move_uploaded_file($_FILES['files']['tmp_name'], $destination);
        return $new_name;
    }
}
?>

<!-- Alert Success -->
<script>
window.setTimeout(function() {
  $(".alert").fadeTo(500, 0).slideUp(500, function(){
    $(this).remove();
  });
}, 5000); //timeout
</script>

The only problem is the file that I can't update. Any ideas? Help is much appreciated. Thanks.

Zack Fair
  • 9
  • 3
  • `` then `$('#file').val(data.file);`. Did you forgot a `s` at `file` ? – Cid Sep 11 '18 at 08:23
  • 1
    if($_FILES["files"]["name"] = '') modify if($_FILES["files"]["name"] == '') – long Sep 11 '18 at 08:25
  • 1
    I would recommend you to use Prepared Statements instead of `mysqli_real_escape_string()` (it actually does have security holes in some edge cases). You're also escaping numbers, and as the name of the function suggests, it's for strings, not numbers. You're also wide open to SQL Injection attacks since you're not escaping the `$_POST['id']` at all. _Never_ trust user data. – M. Eriksson Sep 11 '18 at 08:37
  • Possible duplicate of [jQuery AJAX file upload PHP](https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php). However, that's just one of many issues with this code. – M. Eriksson Sep 11 '18 at 08:46

2 Answers2

0

I think ,you are assigning the name of file via input field.if somebody does not assign the value via input filed ,you have used the method upload_file() .so try to change your if with $_POST["file"] = '' which check whether name is assigned or not ,if assigned the used given else used name define in your upload_file().

<?php
$connect = mysqli_connect("localhost", "root", "", "record");
if(!empty($_POST))
{
  $output = '';
  $message = '';

  $ctrl_no = mysqli_real_escape_string($connect, $_POST["ctrl_no"]);
  $title = mysqli_real_escape_string($connect, $_POST["title"]);
  $category = mysqli_real_escape_string($connect, $_POST["category"]);
  $fname = mysqli_real_escape_string($connect, $_POST["fname"]);
  $adate = mysqli_real_escape_string($connect, $_POST["adate"]);
  $createdby = mysqli_real_escape_string($connect, $_POST["createdby"]);

  //file upload

  $file = '';
//make the change here in if
  if($_POST["file"] = '')
  {
    $file = upload_file();
  }
  else
  {
    $file = $_POST["file"];
  }

  if($_POST["id"] != '')
  {
    $query = "
    UPDATE `dashboard`
    SET
    `ctrl_no`='$ctrl_no',
    `title`='$title',
    `category`='$category',
    `file`='$file',
    `fname`='$fname',
    `adate` = '$adate',
    `createdby` = '$createdby'
    WHERE `id`='".$_POST["id"]."'";
    $message = 'Data Updated.';
  }

  if(mysqli_query($connect, $query))
  {
    $output .= "<div class='alert alert-success alert-dismissible'>
    <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
    <strong>Success!</strong> $message
    </div>";
    $select_query = "SELECT * FROM `dashboard` ORDER BY `id` DESC";
    $result = mysqli_query($connect, $select_query);
    $output .= '
    <table id="dataTable" style="width:100%" class="table table-bordered table-striped table-hover">
    <thead>
    <tr>
    <th width="6%"><b>Date</b></th>
    <th width="8%"><b>Control No.</b></th>
    <th width="37%"><b>Title / Particular</b></th>
    <th width="17%"><b>Category</b></th>
    <th width="10%"><b>From /<br />End-user</b></th>
    <th width="10%"><b>File</b></th>
    <th width="7%"><b>Action</b></th>
    </tr>
    </thead>
    <tbody>
    ';
    while($row = mysqli_fetch_array($result))
    {
      $output .= '';
    }
    $output .= '</tbody></table>';
  }
  echo $output;
}

function upload_file()
{
    if(isset($_FILES["files"]))
    {
        $extension = explode('.', $_FILES['files']['name']);
        $new_name = rand() . '.' . $extension[1];
        $destination = '../file/' . $new_name;
        move_uploaded_file($_FILES['files']['tmp_name'], $destination);
        return $new_name;
    }
}
?>

<!-- Alert Success -->
<script>
window.setTimeout(function() {
  $(".alert").fadeTo(500, 0).slideUp(500, function(){
    $(this).remove();
  });
}, 5000); //timeout
</script>
cool_benn
  • 56
  • 8
  • 3
    A good answer includes an explanation. What was wrong with the OP's code? What have you changed and how does that change solve the issue? Don't let the OP and future visitors go through all code and guess. Also, it's wrong. `if($_POST["file"] = '')` will set the `$_POST['file']` to an empty string. – M. Eriksson Sep 11 '18 at 08:41
  • _"//make the change here in if"_ isn't an explanation. This basically contains as many errors in the code as the original. – M. Eriksson Sep 11 '18 at 08:43
0

Are you sure you get file to server side? if not, you want to pass files as this.(this is example Iam sure you will understand how to fit this to your code). key element is formData :)

var formData = new FormData($("#formid")[0]);
$.ajax({
    url:'url',
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    async: false,
    success:function(response){
        if(response == '100'){
            swal({ 
              title: "Blog Added",
              text: "Blog Added Successfully",
              type: "success",
              confirmButtonText: "OK",
              showCancelButton: false,
            }, function(){
                /*location.reload();*/
                window.location.href = 'redirect link';
            });
        }else{
            toastr.error(response);
        }
    }
}); 

How to pass file data with AJAX and jQuery?

Matas Lesinskas
  • 414
  • 6
  • 13
  • Also describe how code works, what are you doing with data, should file be file or real file and so on :) – Matas Lesinskas Sep 11 '18 at 08:50
  • ...and maybe update the code to fit the OP's code. Example: remove all the code in the `success` callback. `$("#formid")[0]` is also wrong in this context. It's the file-input you should use, not the form. – M. Eriksson Sep 11 '18 at 08:53
  • @MagnusEriksson you can edit if you want Iam just giving example :) – Matas Lesinskas Sep 11 '18 at 09:09
  • I understand but if the OP (or future visitors) doesn't know JS that well, having a bunch of extra code that's not relevant will only confuse. It's important to think about that when you write an answer. Only include the relevant parts. – M. Eriksson Sep 11 '18 at 09:35