Rimjhim Ratnani
Rimjhim Ratnani

Reputation: 113

PHP passing variable id through href

I want to have a link to another page, with particular subject, How can I pass the id ?

<table class="table table-hover">
    <thead>
        <tr>
            <th>Subject</th>
            <th>Add Topic</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <?php foreach($subjects as $sub):?>
            <td><?php echo $sub->subject;?></td>
            <td><a href='approve.php?id=".$sub->id."' role="button" class="btn">Add Topic</a></td>
        </tr>
        <?php endforeach;?>
    </tbody>
</table>

Upvotes: 4

Views: 63102

Answers (4)

Pete
Pete

Reputation: 86

You need to enclose your variable in a PHP tag:

<?php foreach($subjects as $sub):?>
  <tr>
     <td><?php echo $sub->subject;?></td>
     <td><a href='approve.php?id=<?php echo $sub->id ?>' role="button" class="btn">Add Topic</a></td>

   </tr>
<?php endforeach;?>

There is also a short form echo tag enabled on most PHP servers <?= $variable ?>

On the subsequent page you retrieve the parameter from the GET array:

$subject = $_GET['id'];

If you're passing this value to the database you should do some validation:

if ($_GET['id']) { // check parameter was passed
  $subject = int_val($_GET['id']) // cast whatever was passed to integer
} else {
  // handle no subject case
}

Upvotes: 0

Mohammed Joraid
Mohammed Joraid

Reputation: 6490

Yes you can, it will be considered as GET. as for how to pass it. Edit the following:

 <td><a href='approve.php?id=<?=$sub->id?> ' role="button" class="btn">Add Topic</a></td>

This is the part:

 <?=$sub->id?>

You closed php tag when u started adding html therefore open it again to echo php vars.

Upvotes: -1

Kumar Saurabh Sinha
Kumar Saurabh Sinha

Reputation: 870

Please try the following:

<table class="table table-hover">

    <thead>
    <tr>
        <th>Subject</th>
        <th>Add Topic</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach($subjects as $sub):?>
    <tr>


        <td><?php echo $sub->subject;?></td>
        <td><a href='approve.php?id=<?php echo $sub->id; ?>' role="button" class="btn">Add Topic</a></td>

    </tr>
    <?php endforeach;?>
    </tbody>
</table>

and then on the page : approve.php

<?php
$subjectId  = $_GET['id'];
?>

$subjectId will give you the corresponding subject id with which you can move forward with the functionality.

Note: foreach should start either outside <tr> and end outside </tr> or it can be inside <tr> </tr>

Upvotes: 2

xdazz
xdazz

Reputation: 160963

You still need to echo it out.

<?php foreach($subjects as $sub): ?>
    <tr>
    <td><?php echo $sub->subject ?></td>
    <td><a href="approve.php?id=<?php echo $sub->id ?>" role="button" class="btn">Add Topic</a></td>
    </tr>
<?php endforeach; ?>

Upvotes: 4

Related Questions