skip to Main Content

I am trying to use a button to POST a variable from one page in php to another. I have retrieved the variable "Class" from the table "Class" and now want to POST it to the viewmembers.php page, however am unsure how to do this.

Here is the code:

<?php
    
session_start();
    
include_once('connection.php');
    
    
$stmt = $conn->prepare("SELECT * FROM class WHERE Username = :Username");
    
$stmt->bindParam(':Username', $username);
$stmt->execute();  
    
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    echo("Class Code: ".$row["Class"]." <br> Username: " .$row["Username"]." <br> Subject: ".$row["SubjectName"]."<br>");

    echo("<button onclick= "location.href='viewmembers.php'">View Members</button><br><br>");
    
}
?>

I have tried using session variables, however since I have retrieved multiple rows from the table, the session variable only stores the last row that was retrieved from the table. Any help would be appreciated.

2

Answers


  1. It sounds like you just want your page to list each class, and be able to have a link to the viewmembers.php page, and send the class value to that page when it’s clicked on.

    While you mention a POST, this is generally more logical to achieve with a GET request – and simpler as well.

    So instead of

    echo("<button onclick= "location.href='viewmembers.php'">View Members</button><br><br>");
    

    you could write

    echo '<a href="viewmembers.php?class='.$row["Class"].'">View Members</a>';
    

    which would then output a normal HTML hyperlink in the format

    <a href="viewmembers.php?class=abc">View Members</a>
    

    The viewmembers.php page can then read the class variable passed to it by having

    $class = $_GET["class"];
    

    in the code. It can then use that value for whatever purpose you like (e.g. by using it as a parameter in a SQL query to retrieve specific details about that class and its members, and display them).

    Login or Signup to reply.
  2. I’m not sure to understand.

    The href link uses the GET method.

    For a POST method you can use some form(s) like below with the parameters you need.

    <?php 
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
       Class Code: <?php echo $row["Class"];?>
       <br> Username: <?php echo $row["Username"];?> 
       <br> Subject: <?php echo $row["SubjectName"];?> 
       <br>
    
        <form method="post" action="viewmembers.php">
          <input type="hidden" name="Class" value="<?php echo $row["Class"];?>"> 
          <input type="hidden" name="Username" value="<?php echo $row["Username"];?>"> 
          <input type="hidden" name="SubjectName" value="<?php echo $row["SubjectName"];?>"> 
            <button type="submit" class="mybutton">
              View Members
             </button>
          </form>
    <br>
    <br>
    <?php }?>`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search