-3

I have a table of student data and a folder with their images. I want to replace some imges but it is not working. please help. I got this code somewhere and changed it according to my need but it is not working. code is in two parts. The first part is a form with a jquery action part in PHP. please help what is wrong with this code

enter image description here code of photochange.php

    <h1 class="page-head-line">Student Photo Change</h1>

<div class="container" style="width:900px;">  

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

<div id="imageModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Add Image</h4>
   </div>
   <div class="modal-body">
    <form id="image_form" method="post" enctype="multipart/form-data">
     <p><label>Select Image</label>
     <input type="file" name="image" id="image" /></p><br />
     <input type="hidden" name="action" id="action" value="insert" />
     <input type="hidden" name="image_id" id="image_id" />
     <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
      
    </form>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>
 
<script>  
$(document).ready(function(){
 
 fetch_data();

 function fetch_data()
 {
  var action = "fetch";
  $.ajax({
   url:"photochangeaction.php",
   method:"POST",
   data:{action:action},
   success:function(data)
   {
    $('#image_data').html(data);
   }
  })
 }
 $('#add').click(function(){
  $('#imageModal').modal('show');
  $('#image_form')[0].reset();
  $('.modal-title').text("Add Image");
  $('#image_id').val('');
  $('#action').val('insert');
  $('#insert').val("Insert");
 });
 $('#image_form').submit(function(event){
  event.preventDefault();
  var image_name = $('#image').val();
  if(image_name == '')
  {
   alert("Please Select Image");
   return false;
  }
  else
  {
   var extension = $('#image').val().split('.').pop().toLowerCase();
   if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
   {
    alert("Invalid Image File");
    $('#image').val('');
    return false;
   }
   else
   {
    $.ajax({
     url:"photochangephotochangeaction.php",
     method:"POST",
     data:new FormData(this),
     contentType:false,
     processData:false,
     success:function(data)
     {
      alert(data);
      fetch_data();
      $('#image_form')[0].reset();
      $('#imageModal').modal('hide');
     }
    });
   }
  }
 });
 $(document).on('click', '.update', function(){
  $('#image_id').val($(this).attr("id"));
  $('#action').val("update");
  $('.modal-title').text("Update Image");
  $('#insert').val("Update");
  $('#imageModal').modal("show");
 });
 $(document).on('click', '.delete', function(){
  var image_id = $(this).attr("id");
  var action = "delete";
  if(confirm("Are you sure you want to remove this image from database?"))
  {
   $.ajax({
    url:"photochangephotochangeaction.php",
    method:"POST",
    data:{image_id:image_id, action:action},
    success:function(data)
    {
     alert(data);
     fetch_data();
    }
   })
  }
  else
  {
   return false;
  }
 });
});  
</script>

code of photochangeaction.php

<?php

if(isset($_POST["action"]))
{
 
 if($_POST["action"] == "fetch")
 {
  $query = "SELECT id, form_no, sname, photo FROM student  where center_code='1001'";
  $result = mysqli_query($conn, $query);
  $output = '
   <table class="table table-bordered table-striped">  
    <tr>
     <th width="10%">ID</th>
     <th width="70%">Image</th>
     <th width="70%">File Name</th>
     <th width="70%">Student Name</th>
     <th width="10%">Change</th>
     
    </tr>
  ';
  while($row = mysqli_fetch_array($result))
  {
     
   $output .= '

    <tr>
     <td>'.$row["id"].'</td>
     <td>
      <img src="'.($row['photo'] ).'" height="60" width="75" class="img-thumbnail" />
     </td>
     <td>
      '.($row['photo'] ).'
     </td>
     <td>
      '.($row['sname'] ).'
     </td>
     <td><button type="button" name="update" class="btn btn-warning bt-xs update" id="'.$row["id"].'">Change</button></td>
   
    </tr>
   ';
  }
  $output .= '</table>';
  echo $output;
 }

 
 if($_POST["action"] == "update")
 {
  $file = $_FILES["image"]["tmp_name"];
 // $image=PATHINFO($_FILES['image']['name']);
  $form_no=$conn->query('select form_no from student WHERE id = '.$_POST["image_id"].'');
  $newFilename=$form_no . '.' . $file['extension'];
    if (file_exists("sphoto/" . $newfilename))
        {
        // file already exists error
            unlink("sphoto/$newfilename");
            move_uploaded_file($_FILES["image"]["tmp_name"], "sphoto/" . $newfilename);
            $photo='../sphoto/' . $newFilename;
            $query = "UPDATE student SET photo = '$photo' WHERE id = '".$_POST["image_id"]."'";
                if(mysqli_query($conn, $query))
                    {
                        echo 'Image Updated into Database';
                        echo "File Overwritten";
                    }
            
        }
        else
        {       
            move_uploaded_file($_FILES["image"]["tmp_name"], "sphoto/" . $newfilename);
            echo "File uploaded successfully."; 
            $query = "UPDATE student SET photo = '$photo' WHERE id = '".$_POST["image_id"]."'";
                if(mysqli_query($conn, $query))
                    {
                        echo 'Image Updated into Database';
                        echo "File Overwritten";
                    }
        }
 }
}
?>
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman May 02 '22 at 13:20
  • _"it is not working. please help"_ tells us nothing about **what isn't working**, what errors you get, what you've tried to fix it, etc. – Markus AO May 02 '22 at 19:38

1 Answers1

-1

It's dangerous using code made by someone else. I imagine you struggle understanding what some segments do right? UPDATING isn't generally difficult in PHP, if you're just copying then so be it.

In your database (mysql) you can manually update the Images, but since you want it through the website. Here's a guide to assist you. Again I highly suggest building your own environment (doesn't matter if its copied as long as you understand what things do)

guide keyword: update mysql with forms php

Update Mysql with Forms PHP

Wake
  • 73
  • 6
  • sir, the issue is image replacement and update path to the database please help – Sandeep Upadhyay May 02 '22 at 13:44
  • It's dangerous to use any code you don't understand. It's also dangerous to not understand application security basics. The code in the guide you linked is vulnerable to _both_ SQL Injections _AND_ XSS. – Markus AO May 02 '22 at 19:41