php - 单击表格行中的链接后,更改相应 MYSQL 数据库记录的单元格值?

标签 php jquery mysql sql

我有一个 mysql 数据库,其字段结构如下:

id fname lname auxiliary calling releaseFrom user date notes status

我有一个对应于那些相同字段的表。在每一行的最后,我有一个链接,单击该链接后,应将相应行的“状态”字段更改为“已批准”。单击链接后,我无法确定如何指定要更改的记录。我假设我需要以某种方式定位正确行的 ID,但我不知道该怎么做。

This是我拥有的表格的非常基本的设置。单击“已批准”链接时,它应该会更改 MYSQL 数据库记录。有谁知道如何完成我想要做的事情?

最佳答案

第一个解决方案

当你在服务器端构建你的表时,一定要有这样的东西

<td><a href="your_script.php?action=approve&id=<?php echo RECORD_ID ?>">Archive</a></td>

然后 HTML 将如下所示。如您所见,您将为每条记录打印此链接

<!-- HTML --> 
<tr>
    <td>43</td>
    <td>Jerry</td>
    <td>PFR</td>
    <td><a href="your_script.php?action=approve&id=111">Archive</a></td>
</tr>

服务器端的代码应该是这样的

//PHP [your_sccript.php]
if(isset($_GET['action']) && $_GET['action'] == 'approve'){
    mysqli_query("
      UPDATE your_table
      SET status = 'approved'  // or use an integer, 1 in this case
      WHERE id = " . $_GET['id'] . "
   ");
   // if you use the second solution echo something here to the console, like
   echo "Post " . $_GET['id'] . " has been approved";
}

第二种解决方案

如果您不想在每次单击 Archive 链接后​​重新加载您的页面,请使用 Ajax。

这是由 PHP 在服务器端生成的表格行。您可能会注意到,JavaScript approve() 函数现在有两个参数;第二个是记录的 id 而第一个是被点击元素的引用。

<!-- HTML --> 
<tr>
    <td>43</td>
    <td>Jerry</td>
    <td>PFR</td>
    <td><span onclick="approve(this, 111);">Archive</span></td>
</tr>

// JavaScript
var approve = function(obj, id){
  var xhr = new XMLHttpRequest();
  var url = "your_script.php?action=approve&id=" + id;
  xhr.open("GET", url, true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // at this point we need to get the first parent TR to whom the SPAN belongs
      // if you want to replace only the TD (the parent of the SPAN)
      // change the TR to TD within the while loop below
      var tr = obj.parentNode;
      while(tr.nodeName != 'TR'){
        tr = tr.parentNode;
      }
      // as we have it, let's replace it with the response (new row) from the server
      tr.outerHTML = xhr.responseText;
    }
  };
  xhr.send();
};

// PHP
if(isset($_GET['action']) && $_GET['action'] == 'approve'){
  // first, update the row
  mysqli_query("UPDATE table SET status = 1 WHERE id = " . $_GET["id"] . "");
  // and then select, and echo it back like this 
  $set = mysqli_query("SELECT * FROM table WHERE id = " . $_GET["id"] . "");
  $row = mysqli_fetch_array($set, MYSQLI_ASSOC);
  echo '<TR>' . 'ALL_THE_TD' . '</TR>';
  // so, we echo the same row, but the updated one
  // this will be used by JavaScript function to replace the old TR 
}

关于php - 单击表格行中的链接后,更改相应 MYSQL 数据库记录的单元格值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25318271/

相关文章:

php - php 中的 exec 工作不当

php - 谷歌地图地理定位不请求许可

jquery - 单个页面中多个拖放区的全局选项

javascript - 如何在 session 中或本地以 Angular 存储数据..?

php - Doctrine2实体自定义加入

php - 如何获取 mPDF 文档中的页数?

php - MySQL 查询确实需要很长时间才能加载然后超时

javascript - 在动态创建的 UL 上使用 Sortable

php - goto 在 php 中不工作给出语法错误,第 10 行出现意外的 ':'

mysql - sails.js 多对多关系连接表的额外字段