简体   繁体   English

使用 PHP 从加载的表中获取 MySQL ID

[英]Get MySQL ID from loaded table with PHP

I am trying to get the ID from a specific table row when I click on it.当我点击它时,我试图从特定的表格行中获取 ID。 I have the following PHP code:我有以下 PHP 代码:

$sql = "SELECT ID, eventName, DATE_FORMAT(date, '%d/%m/%Y'), time, aantal_spelers, current_spelers FROM dutch_delight ORDER BY date, time";
                $result = $conn->query($sql);



                if ($result->num_rows > 0) {
                    while($row = $result->fetch_assoc()) {
                        echo "<tr><td>".$row["DATE_FORMAT(date, '%d/%m/%Y')"]."</td>"."<td>".$row["time"]."</td>"."<td>".$row["eventName"]."</td>"."<td>".$row["aantal_spelers"]."</td>"."<td>".$row["current_spelers"]."</td></tr>";
                    }

                } 

                else {
                    echo "Er zijn nog geen evenementen aangemaakt.";
                }

Now, What I want to do is when I click on a specific table row it will alert the ID of this row.现在,我想要做的是当我单击特定的表格行时,它会提醒该行的 ID。 So if there are 30 rows and I click the 10th one, I need to display the correct ID.因此,如果有 30 行并且我单击第 10 行,则需要显示正确的 ID。 Does anyone have an idea on how to do this?有没有人知道如何做到这一点?

 echo "<tr onclick=\"alert('".$row['ID']."')\"><td>".$row["DATE_FORMAT(date, '%d/%m/%Y')"]."</td>"."<td>".$row["time"]."</td>"."<td>".$row["eventName"]."</td>"."<td>".$row["aantal_spelers"]."</td>"."<td>".$row["current_spelers"]."</td></tr>";

you can use jquery/javascript for this您可以为此使用 jquery/javascript

if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    echo "<tr onclick=\"alert('".$row['ID']."')\"><td>".$row["DATE_FORMAT(date, '%d/%m/%Y')"]."</td>"."<td>".$row["time"]."</td>"."<td>".$row["eventName"]."</td>"."<td>".$row["aantal_spelers"]."</td>"."<td>".$row["current_spelers"]."</td></tr>";
                }

Here use onclick event on TR to alert the Ids.every row has their own ID whenever you click on the table row corresponding ID will pop-up.这里使用 TR 上的 onclick 事件来提醒 Ids。每当您单击表格行时,每行都有自己的 ID,相应的 ID 将弹出。

in your while you need to give for any rows a id在您的同时,您需要为任何行提供一个 id

echo '<tr id="'.$row['ID'].'"><td>......</td></tr>';

and including in your file the javascript并在您的文件中包含 javascript

<script>
var table = document.querySelector('table');

table.addEventListener('click', function(ev){
    var theID = ev.target.id;
    alert(theID);
})
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM