我有一个mysql数据库,其字段结构如下:
id fname lname auxiliary calling releaseFrom user date notes status
我有一个对应于那些相同字段的表。在每一行的最后,我有一个链接,当点击时,应该更改“状态”'相应行的字段为'已批准'。我在查找如何指定单击链接后要更改的记录时遇到一些问题。我假设我需要以某种方式确定正确行的ID,但我无法弄清楚如何做到这一点。
This是我所拥有的桌子的一个非常基本的设置。当批准'单击链接,然后应该更改MYSQL数据库记录。有谁知道如何完成我想要做的事情?
答案 0 :(得分:2)
第一个解决方案
在服务器端构建表时,请务必使用此类
<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
}