PHP AJAX - 数据更新/编辑作为新数据插入而不是更新

Posted

技术标签:

【中文标题】PHP AJAX - 数据更新/编辑作为新数据插入而不是更新【英文标题】:PHP AJAX - data update/edit inserts as new data instead of updating 【发布时间】:2022-01-07 18:09:20 【问题描述】:

数据插入和删除工作正常。但是,edit 不会更新数据。相反,它会插入一个新的..

我在一个文件中有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; 
      
     );
);

这是HTML 表单:

<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>

【问题讨论】:

我刚刚注意到,if (isset($_POST["traffic_operation"]) == "Add") 这将始终为假,因为您将 isset() 的结果与字符串“Add”进行比较,这可能是真/假。 【参考方案1】:

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

$_POST["traffic_operation"]) 的输出将为 TRUE 或 FALSE。

所以替换下面的行

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

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

【讨论】:

很好,但现在我遇到了错误...SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 91 此问题与您执行的查询的绑定参数有关。

以上是关于PHP AJAX - 数据更新/编辑作为新数据插入而不是更新的主要内容,如果未能解决你的问题,请参考以下文章

AJAX PHP MYSQL 更新/编辑记录 (jQuery)

内联可编辑行以使用 ajax php 更新数据库 mysql 中的每个记录

Ajax更新,比较和插入数据到mysql

PHP / MySQL / AJAX - 更新多个数据

php - ajax 问题 - 数据预置/附加中的一键延迟

更新选择列表而不刷新 [PDO/PHP/AJAX]