首页 > 解决方案 > 获取 id 以在模式中使用以更新 php 中的数据库的方法

问题描述

所以我的目的是从数据库中获取 ID 并使 id 准备好用于模态。我知道我可以使用input type=hidden,但我不确定它是否安全,因为在检查元素中,用户可以编辑它。我也在考虑,session但我不知道我该怎么做。那么提交后我可以做些什么来使id不可编辑呢?或者我怎样才能把它放在数组中并匹配 id?这是我使用的代码

类名.php

public function getAllNames()
{
  $obj = new Db();
  $stmt = $obj->connect()->query("SELECT * FROM persons");
  while ($person = $stmt->fetch())
  {
    echo "<tr>";
    echo "<td>".$person['first_name']."</td>";
    echo "<td>".$person['last_name']."</td>";
    echo "<td><a id=\"".$person['person_id']."\"type=\"button\" data-target-toggle=\"modal\" data-target=\"#edit-name-modal\" class=\"btn btn-danger edit_data\" href=\"#\">Update</a></td>";
    echo "</tr>"; 
  }
}

名称.js

$(document).on('click', '.edit_data', function(){  
 var person_id = $(this).attr("id");
 $.ajax({  
      url:"/data/updatename.php",
      method:"POST",
      data:{person_id:person_id},
      dataType:"json",  
      success:function(data){
        $('#first_name').val(data.first_name);
        $('#last_name').val(data.last_name);
        $('#person_id').val(data.person_id);
        $('#edit-name-modal').modal('show');         
      }  
 });  
});

更新名称.php

<?php
include_once 'db.php';  
if(isset($_POST["person_id"]))  
{  
  $person_id = $_POST["person_id"]; 
  $object = new Dbc();
  $stmt = $object->connect()->prepare("SELECT * FROM persons WHERE person_id=?");
   $stmt->execute([$person_id]);  
  $profile_info = $stmt->fetch();
  echo json_encode($profile_info);    
}
?>

名称列表.php

<div class="modal fade" id="edit-name-modal" name="edit-name" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <form method="POST" enctype="multipart/form-data" action="namelist.php">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Update Name's List</h4>
      </div>

      <div class="modal-body">
        <div class="form-group">
          <label>First Name</label>
          <input type="text" id="first_name" name="first_name" class="form-control">
        </div>

        <div class="form-group">
          <label>Last Name</label>
          <input type="text" id="last_name" name="last_name" class="form-control">
        </div>
        <input type="hidden" id="person_id" name="person_id">

        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="submit" name="update" class="btn btn-primary">Update</button>
        </div>
      </div>
    </form>
  </div>

标签: phphtmlajax

解决方案


推荐阅读