Search code examples
phppostget

Passing id from foreach loop to another page without using $_GET (id in url)


For now I have this code which passes variables based on an id in the URL:

 foreach ($allUnsteadyState as $list) {
                    ?>
                    <tr>
                        <td><?php echo $list['project_name'] ?></td>
                        <td><?php echo $list['project_date'] ?></td>
                        <td><a href="unsteady_state_user.php?id=<?php echo $list['id'] ?>">Go to project</a></td>
                    </tr>
                    <?php
                }
                ?>

And catch it on another page through an function with this code:

 $id = (int)$_GET['id'];
    $db = $this->dbconn;
    try {
        $stmt = $db->prepare("SELECT * FROM unsteady_state WHERE id = :id ");
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetchAll();

And so on.

For security reasons I don't want to show the id in the url, so I tried to use $_POST and $_SESSION without succes. Can someone help me with this please?


Solution

  • You can do this with $_POST. You'll need a form. You can wrap one around your table.

    <form action="unsteady_state_user.php" method="post">
        <table>...</table>
    </form>
    

    Then use buttons instead of links.

    <?php foreach ($allUnsteadyState as $list): ?>
      <tr>
        <td><?php echo $list['project_name'] ?></td>
        <td><?php echo $list['project_date'] ?></td>
        <td>
          <button type="submit" name="id" value="<?php echo $list['id'] ?>">
            Go to project
          </button>
        </td>
      </tr>
    <?php endforeach; ?>
    

    The ID won't be in the URL. You can get it from $_POST['id']

    However, it will still be in the page source so depending on what your security concerns are this may not work for you.