Jop Rill
Jop Rill

Reputation: 65

How can I get an ID from a SQL filled table?

I made a table which is filled with SQL data. When I click on a row, it takes me to a different page (using javascript). On this page I want to show all the data from the clicked row only. How can I get the ID from a table filled with SQL data? Im talking about the ID of the SQL row.

echo "<table>"; 
                                            echo "<tr>";
                                            echo "<th>".'Stof'."</th>";
                                            echo "<th>".'Score'."</th>";
                                            echo "<th>".'Datum'."</th>";
                                            echo "</tr>";
                                            foreach ($result as $pers) {
                                                echo "<tr data-href='detail.php'>";
                                                echo "<td>".$pers->stofid."</td>
                                                <td>".$pers->melden."</td>
                                                <td>".$pers->datum."</td>";
                                                echo "</tr>";
                                            }
                                            echo "</table>";

The data-href is my page reference, and it works.

Upvotes: 2

Views: 56

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

To show ID in table add this before last line in your foreach statement:

echo "<td>".$pers->id."</td>"

And don't forget to add th element in your table tr section (above foreach)

echo "<th>id</th>";

And if you wanna pass that ID to next page (detail.php) then change first line in your foreach statement into this:

echo "<tr data-href='detail.php?persId=".$pers->id."'>";

Upvotes: 1

wizzwizz4
wizzwizz4

Reputation: 6426

Unless you put the id in the table somewhere, it's not possible. I recommend doing the following:

echo "<table>"; 
echo "<tr>";
echo "<th>".'Stof'."</th>";
echo "<th>".'Score'."</th>";
echo "<th>".'Datum'."</th>";
echo "</tr>";
foreach ($result as $pers) {
    echo "<tr data-href='detail.php' data-id='".$pers->id."'>";
    echo "<td>".$pers->stofid."</td>
          <td>".$pers->melden."</td>
          <td>".$pers->datum."</td>";
    echo "</tr>";
}
echo "</table>";

That way, you can change whatever JavaScript code turns your data-href into a link into code that generates detail.php?id=34526 (using the data-id value also. Then detail.php can, if it receives an id $_GET parameter, only show details from that row. (Make sure the user's allowed to read the row with that id, or you'll be introducing a security vulnerability!)

Upvotes: 1

Related Questions