简体   繁体   中英

Get the row number in the table and save it into php variable

I'm using while loop to display the data from the database into a table. It should allow user to redirect to other page to edit the information when user clicks on any of the row. I am trying to get the row number which the user clicked on, and need to convert to a php variable. How can i do this? Is there other way to get the row number? Here is my code:

<div id="table-wrapper">
  <div id="table-scroll">
    <table class="table" border="1" border-spacing="2" padding="2" >
      <tr class="row">
        <td>
          <font face="Arial, Helvetica, sans-serif">Staff ID</font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif">Name</font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif">Position</font>
        </td>
      </tr>

      <?php
        $i = 0;
        while ($i < $num) {
          $f1 = mysql_result($result, $i, "ID");
          $f2 = mysql_result($result, $i, "Name");
          $f3 = mysql_result($result, $i, "Position");
      ?>

      <script>
        function myFunction(x) {
          alert("Row index is: " + x.rowIndex);
          //i can get the row number using this
        }
      </script>

      <tr onclick="myFunction(this)">
        <td>
          <font face="Arial, Helvetica, sans-serif"><?php echo $f1;  ?></font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif"><?php echo $f3; ?></font>
        </td>
      </tr>

      <?php
          $i++;
        }  
      ?>
    </table>
  </div>
</div>

It would be best to use an actual link, assuming that you're going to make a standard GET request (if not, please expand a bit on what it is that you're trying to do):

<td>
  <a href="path/to/some_script.php?n=<?php echo $i ?>">
    <font face="Arial, Helvetica, sans-serif"><?php echo $f1 ?></font>
  </a>
</td>

If you must use JavaScript, you could also store the number as data, which might be a bit more reliable:

<script>
    function myFunction(el) {
        alert(el.dataset.row);
    }
</script>

<tr data-row="<?php echo $i ?>" onclick="myFunction(this)">
  <font face="Arial, Helvetica, sans-serif"><?php echo $f1 ?></font>
</td>

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