PHP AJAX - data update/edit inserts as new data instead of updating

Data插入并删除工作正常。然而edit没有更新数据。相反,它插入了一个新的。

I have INSERTUPDATE在一个文件中,用if conditions:

<?php

include ("./backend/config/connection.php");
include ("./backend/config/function.php");

if (isset($_POST["traffic_operation"])) {
    if (isset($_POST["traffic_operation"]) == "Add") {
        $traffic_doc = "";

        if ($_FILES["traffic_doc"]["name"] != "") {
            $traffic_doc = upload_image();
        }
        $statement = $connection->prepare('INSERT INTO traffic_violations (
                     plateNumber,
                     carModel,
                     carColor,
                     violationType,
                     ownerGender,
                     violationDateTime,
                     violationLocation,
                     workingShift,
                     violationAction,
                     violationStatement,
                     cccEmployee
              ) VALUES (
                     :plate_number,
                     :car_model,
                     :car_color,
                     :violation_type,
                     :owner_gender,
                     :violation_date,
                     :violation_location,
                     :working_shift,
                     :violation_action,
                     :traffic_doc,
                     :ccc_employee
                     )
              ');
        $result = $statement->execute([
            ":plate_number" => $_POST["plate_number"],
            ":car_model" => $_POST["car_model"],
            ":car_color" => $_POST["car_color"],
            ":violation_type" => $_POST["violation_type"],
            ":owner_gender" => $_POST["owner_gender"],
            ":violation_date" => $_POST["violation_date"],
            ":violation_location" => $_POST["violation_location"],
            ":working_shift" => $_POST["working_shift"],
            ":violation_action" => $_POST["violation_action"],
            ":traffic_doc" => $traffic_doc,
            ":ccc_employee" => $_POST["ccc_employee"],
        ]);
        if (!empty($result)) {
            echo 'Traffic Violation Added';
        }
    }

    if ($_POST["traffic_operation"] == "Edit") {
        $traffic_doc = "";

        if ($_FILES["traffic_doc"]["name"] != "") {
            $traffic_doc = upload_image();
        }

        $statement = $connection->prepare('UPDATE traffic_violations SET
                     plateNumber = :plate_number,
                     carModel = car_model,
                     carColor = car_color,
                     violationType = violation_type,
                     ownerGender = owner_gender,
                     violationDateTime = violation_date,
                     violationLocation = violation_location,
                     workingShift = working_shift,
                     violationAction = violation_action,
                     violationStatement = traffic_doc,
                     cccEmployee = ccc_employee,
                     WHERE id = :id');
        $result = $statement->execute([
            ":id" => $_POST["violation_id"],
            ":plate_number" => $_POST["plate_number"],
            ":car_model" => $_POST["car_model"],
            ":car_color" => $_POST["car_color"],
            ":violation_type" => $_POST["violation_type"],
            ":owner_gender" => $_POST["owner_gender"],
            ":violation_date" => $_POST["violation_date"],
            ":violation_location" => $_POST["violation_location"],
            ":working_shift" => $_POST["working_shift"],
            ":violation_action" => $_POST["violation_action"],
            ":traffic_doc" => $traffic_doc,
            ":ccc_employee" => $_POST["ccc_employee"],
        ]);
        if (!empty($result)) {
            echo "Traffic Violation Updated";
        }
    }
}
?>

我也使用ajax:

$(document).ready(function() {
   $("#add_btn").on('click', function() {
      $("#traffic_violation_form")[0].reset();
      $(".violation-title").text("Add New Violation");
      $("#traffic_action").val("Add");
      $("#traffic_operation").val("Add");
      $("#traffic_doc").html('');
   });

   var dataTable = $('.violation_data').DataTable({
      "processing": true,
      "serverSide": true,
      "order": [],
      "ajax": {
         url: "/traffic-fetch",
         type: "POST"
      },
      "columnDefs": [
         {
            "target": [0, 3, 4],
            "orderable": false
         }
      ]
   });

   // For Inserting New Violation
   $(document).on('submit', '#traffic_violation_form', function(e){
      e.preventDefault();

      var plateNumber = $("#plate_number").val();
      var carModel = $("#car_model").val();
      var carColor = $("#car_color").val();
      var ownerGender = $("#owner_gender").val();
      var violationType = $("#violation_type").val();
      var violationLocation = $("#violation_location").val();
      var workingShift = $("#working_shift").val();
      var violationAction = $("#violation_action").val();
      var violationStatement = $("#traffic_doc").val().split('.').pop().toLowerCase();
      var cccEmployee = $("#ccc_employee").val();

      if(violationStatement != '') {
         if( $.inArray(violationStatement, ['jpg', 'jpeg', 'JPG', 'JPEG', 'png', 'PNG', 'webp', 'WEBP']) == -1 ) {
            alert('Invalid file type.');
            $("#traffic_doc").val();
            return false;
         }
      }
      if( plateNumber !='' && carModel !='' && carColor !='' && ownerGender !='' && violationType !='' && violationLocation !='' && workingShift !='' && violationAction !='' && cccEmployee !='') {
         $.ajax({
            url: "/traffic-insert",
            method: "POST",
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            success: function(data) {
               $("#traffic_violation_form")[0].reset();
               $("#trafficModal").modal('hide');
               dataTable.ajax.reload();
            }
         });
      }
      else {
         alert('Nothing should left empty!');
      }
   });

   // For Updating Violation
   $(document).on('click', '.update', function(){
      var violation_id = $(this).attr("id");
      $.ajax({
       url:"/traffic-edit",
       method:"POST",
       data:{violation_id:violation_id},
       dataType:"json",
       success:function(data)
       {
         $("#trafficModal").modal('show');
         $(".violation-title").text("Edit Violation");
         
         $("#violation_id").val(violation_id);

         $("#plate_number").val(data.plate_number);
         $("#car_model").val(data.car_model);
         $("#car_color").val(data.car_color);
         $("#owner_gender").val(data.owner_gender);
         $("#violation_type").val(data.violation_type);
         $("#violation_location").val(data.violation_location);
         $("#working_shift").val(data.working_shift);
         $("#violation_action").val(data.violation_action);
         $("#ccc_employee").val(data.ccc_employee);

         $("#user_uploaded_image").html(data.violationStatement);

         $("#traffic_action").val("Edit");
         $("#traffic_operation").val("Edit");
       }
      })
     });

     $(document).on('click', '.delete', function(){
      var violation_id = $(this).attr("id");
      if(confirm("Are you sure you want to delete this?"))
      {
       $.ajax({
        url:"/traffic-delete",
        method:"POST",
        data:{violation_id:violation_id},
        success:function(data)
        {
         alert(data);
         dataTable.ajax.reload();
        }
       });
      }
      else
      {
       return false; 
      }
     });
});

And here is the HTMLForm:

<form name="traffic_violation_form" id="traffic_violation_form" action="/traffic-process" method="POST" enctype="multipart/form-data">
          <div class="modal-body" id="violation-data">
            <div class="form-row">
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="plate_number">Plate Number</label>
                  <div class="input-group">
                    <div class="input-group-prepend">
                      <span class="input-group-text">Plate #</span>
                    </div>
                    <input type="text" class="form-control" id="plate_number" name="plate_number" >
                  </div>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="car_model">Vehicle Model</label>
                  <div class="input-group">
                    <input type="text" class="form-control" id="car_model" name="car_model" >
                  </div>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="car_color">Vehicle Color</label>
                  <div class="input-group">
                    <input type="text" class="form-control" id="car_color" name="car_color" >
                  </div>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="owner_gender">Owner Gender</label>
                  <div class="input-group">
                    <select class="form-control" name="owner_gender" id="owner_gender" data-toggle="select" >
                      <option value="" disabled selected>Select Gender</option>
                      <option value="Male">Male</option>
                      <option value="Female">Female</option>
                      <option value="No driver">No Driver</option>
                    </select>
                  </div>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="violation_type">Violation Type</label>
                  <select data-toggle="select" class="form-control" name="violation_type" id="violation_type" >
                    <option value="" disabled selected>Select violation type</option>
                    <option value="Speeding">Speeding</option>
                    <option value="Drifting">Drifting</option>
                    <option value="Pass traffic light">Pass traffic light</option>
                  </select>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="violation_location">Violation Location</label>
                  <select class="form-control" name="violation_location" id="violation_location" data-toggle="select" >
                    <option value="" disabled selected>Select Location</option>
                    <option value="Baylasun">Baylasun</option>
                    <option value="Baylasun Hotel">Baylasun Hotel</option>
                    <option value="AL-Waha">AL-Waha</option>
                    <option value="Al-Morooj">Al-Morooj</option>
                    <option value="Royal Green">Royal Green</option>
                    <option value="Beach Towers">Beach Towers</option>
                    <option value="Emmar Building">Emmar Building</option>
                    <option value="Industrial Area (East)">Industrial Area (East)</option>
                    <option value="Industrial Area (West)">Industrial Area (West)</option>
                    <option value="Hejaz Gate">Hejaz Gate</option>
                    <option value="Gate 3">Gate 3</option>
                    <option value="Marina 1">Marina 1</option>
                    <option value="Marina 2">Marina 2</option>
                    <option value="Marina 3">Marina 3</option>
                    <option value="Tala Garden">Tala Garden</option>
                    <option value="AL-Shorooq">AL-Shorooq</option>
                    <option value="Yam Beach">Yam Beach</option>
                    <option value="Sales Center">Sales Center</option>
                  </select>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="violation_date">Violation Created At</label>
                  <input class="form-control" type="datetime-local" name="violation_date" id="violation_date" >
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="working_shift">Working Shift</label>
                  <select class="form-control" name="working_shift" id="working_shift" data-toggle="select" >
                    <option value="" disabled selected>Select Shift</option>
                    <option value="Morning">Morning (A)</option>
                    <option value="Evening">Evening (B)</option>
                    <option value="Night">Night (C)</option>
                  </select>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="traffic_doc">Violation Statement</label>
                  <input type="file" class="form-control" id="traffic_doc" name="traffic_doc" >
                  <span id="user_uploaded_image"></span>
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="ccc_employee">CCC Employee</label>
                  <input type="text" class="form-control" id="ccc_employee" name="ccc_employee" >
                </div>
              </div>
              <div class="col-md-12 mb-3">
                <div class="form-group">
                  <label class="form-control-label" for="violation_action">Violation Action</label>
                  <textarea class="form-control" name="violation_action" id="violation_action" ></textarea>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <input type="hidden" name="violation_id" id="violation_id" />
            <input type="hidden" name="traffic_operation" id="traffic_operation" />
            <input type="submit" name="traffic_action" id="traffic_action" class="btn btn-primary" value="Add" /> 
          </div>
        </form>
I just noticed, if (isset($_POST["traffic_operation"]) == "Add") this will be always false, because you compare result of isset() which could be true/false only with string "Add".Diavolic

回答 1

  1. 赞同 1

    问题在于您试图与“添加”进行比较

    产出$ _ post [“traffic_operation”])是真或假的。

    所以更换以下行

    if (isset($_POST["traffic_operation"]) == "Add")
    

    with

    if ( (isset($_POST["traffic_operation"]) AND ($_POST["traffic_operation"] == "Add") )
    

    John Doe
    NICE,但现在我收到了一个错误......SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 91abdulrahman mushref
    此问题与执行查询的绑定参数有关。John Doe