简体   繁体   中英

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. I have the following PHP code:

$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. So if there are 30 rows and I click the 10th one, I need to display the correct 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

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.

in your while you need to give for any rows a id

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

and including in your file the javascript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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