Error occurs while updating data in MySQL using CSV file

I need help here. I am creating a system where the user will be able to update the product stock by uploading the stock of the products according to the id that has been assigned to the product.
this is how my products table in looks like in mysql database
image
I tried the code below but all i could not update my data into my database. And there’s not error shown on my code. I do not know what is wrong with my codes. Please help me.
below the code that i use for uploading the CSV file to the data of my product_stock.

<?php 
include 'conn.php';
if(isset($_POST["add_stock"]))
{
 if($_FILES['product_file']['tmp_name'])
 {
  $filename = explode(".", $_FILES['product_file']['tmp_name']);
  if(end($filename) == "csv")
  {
   $handle = fopen($_FILES['product_file']['tmp_name'], "r");
   while($data = fgetcsv($handle))
   {
    $product_id = mysqli_real_escape_string($conn, $data[0]);
    $product_stock = mysqli_real_escape_string($conn, $data[1]);  
    $product_status = 1 ;
    $query = "UPDATE products SET `product_stock` = '$product_stock', `product_status` = '$product_status' WHERE id = '$product_id'";
    mysqli_query($conn, $query);
   }
   fclose($handle);
   header("location: upload-product.php?updation=1");
  }
  else
  {
   echo '<script>alert("An error occur while uploading product. Please try again.")
   window.location.href = "upload-product.php"</script>';
  }
 }
 else
 {
  echo '<script>alert("No file selected! ")
  window.location.href = "upload-product.php"</script>';
 }
}
if(isset($_GET["updation"]))
{
  echo '<script>alert("Product Stock Updated successfully!")</script>';
}
?>

 <div class="col-12">
            <div class="card card-user">
              <div class="card-header">
                <h5 class="card-title">Update Product Stock</h5>
                <div class="card-body">
                <div class="form-group">
				<label for="file">Update Products stock File (.csv file)</label>
                <a href="assets/templates/product-template.xlsx" title="Download Sample File (Fill In Information and Export As CSV File)" class="mx-2">
				<span class="iconify" data-icon="fa-solid:download" data-inline="false">
				</a>
                </div>
                <form class = "form" action="" method="post" name="uploadCsv" enctype="multipart/form-data">
                <div>
                <input type="file" name="product_file" accept=".csv">
                <div class="row">
                <div class="update ml-auto mr-auto">
                <button type="submit" class="btn btn-primary btn-round" name="add_stock"> Import .cvs file</button>
                </div>
                </div>
                </div>
                </div>
                </form>
                </div>
              </div>

This is the template that i require user to key in and saved it in CSV format before uploading it.
image

Your thread title indicates an error occurs, but your statement says that no error is shown. It cannot be both. What exact error or symptom are you getting after you submit the form?

Next, if you are doing this for real, you would not store the inventory/stock amount as a single value that gets updated. You would have a stock accounting table, where a new row gets inserted for every plus or minus transaction that affects the stock amount.

Ignoring that point, your code doesn’t have error handling that will tell you if and why it isn’t working, and some of the error handling is misleading in what it is actually doing. Your form processing code should -

  1. Detect if a post method from was submitted before referencing any of the form data. You should not try to test if the submit button is set. It won’t be set in some normal cases for a successful form submission.
  2. If the total size of the form data exceeds the post_max_size setting on the server, both the $_POST and $_FILES arrays will be empty (this is what I think is probably occurring now.) You must detect this condition and setup a message for the user telling them that the size of the form data was too large and could not be processed. You would also log information about this so that you know it is occurring, and could then increase the post_max_size setting if appropriate.
  3. Once you have determined that there is data in the $_FILES array, you need to test the [‘error’] element. If there is no upload error, you can use the uploaded file information, and continue processing the file. For upload errors that the user has control over, you would setup and display a unique and helpful message telling the user what they did wrong and how to correct the problem. For the upload errors that the user has no control over, you would setup and display a general failure message, and log all the information about the error that did occur, so that you can find and fix what’s causing the problem.
  4. Note: the ‘failure’ code for a conditional if/else test is often shorter than the ‘success’ code. If you reverse the condition being tested and put the ‘failure’ code first, it will make your code easier to read.
  5. Testing if the tmp_name is a true/false value doesn’t only mean that no file was selected. It will be a false value for some of the possible upload errors. Once you do item #3 on this list, this conditional test will go away. If no file was selected, the [‘error’] element will be UPLOAD_ERR_NO_FILE (4) and you can setup a specific error message for the user.
  6. The file extension validation needs to be case-insensitive. The current code only allows exactly “csv”. If someone uploads a file with Csv, CSV, or any other combination of letter-case, the test will fail. Also, the error message you are outputting is “An error occur while uploading product. Please try again.” This is incorrect and doesn’t tell the user exactly what was wrong with what they did and how to correct the problem.
  7. The fopen() statement can fail due to an error (temp folder path, permission problems.), You should always have error handling for every statement that can fail. You would setup and display a general failure message for the user and log all the actual information about the error so that you can find and fix what’s causing the problem. You would only run the dependent file logic if the fopen is successful so that you don’t produce follow-on php errors having nothing to do with the actual problem.
  8. You must validate all input data before using it. User submitted data can be anything and cannot be trusted. If either of the two fields you are using are empty (strings) or do not consist of valid integers, don’t use the data. Also, you must detect and ignore blank lines in the csv data.
  9. Running a query inside of a loop is one of the most inefficient things you can do on a web page (the communications between php and the database server are the bottle-neck.) To reduce the communications needed, use a prepared query, prepared once before the start of the looping. This will also eliminate the _escape_string() statements, which aren’t secure if you haven’t set the character set that php is using, to match the character set of your database table.
  10. Again, you always need error handling for statements that can fail. For database statements that can fail - connection, query, prepare, and execute, the easiest way of adding error handling, without needing to add logic at each statement, is to use exceptions for errors and in most cases let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will ‘automatically’ get displayed/logged the same as php errors.)
  11. Every redirect needs an exit/die statement after it to stop php code execution.
  12. The only redirect you should have in post method form processing code should be, upon successful completion, to the exact same url of the current page. Adding the updation=1 to the url is a different url and the browser will re-submit the form data if the user navigates back to the original url of the page. To display a one-time success message, store it in a session variable, then test, display, and clear the session variable at the appropriate location in the html document. For the validation/user error message display, you should use an array to hold the error messages, then just test and display the content of this array at the appropriate location in the html document. This will let you display all the errors at once (when you have more than one form field) so that the user can fix as many of the problems as possible at one time.

You also have at least one out of place </div> tag in the html markup. You should validate your resulting web pages at validator.w3.org

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service