How do you post data with a link


I have a database which holds the residents of each house in a certain street. I have a 'house view' php web page which can display an individual house and residents when given the house number using 'post'. I also have a 'street view' web page which gives a list of houses. What I want to know is if you can have links on the street view which will link to the house view and post the house number at the same time without setting up a form for each?


1/8/2009 10:39:49 PM

Accepted Answer

I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:

<a href="house.php?id=<?php echo $house_id;?>">
  <?php echo $house_name;?>

Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.

4/10/2014 2:58:49 AM

If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:

function formSubmit(house_number)
  document.forms[0].house_number.value = house_number;

Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:

<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">

foreach ($houses as $id => name)
    echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";

That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow