I want to pass a select option value through hyperlink to the next page and for this I have this code:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<form name="search_form" role="form" method="GET" id="search_form" action="SearchResults.php">
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM attributes WHERE attributename='mushtype'");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select id="mushtype" name="mushtype">
<option value="*" selected>Mushroom types</option>
<?php foreach($data as $row): ?>
<option value="<?php echo $row['idattributevalue']; ?>"><?php echo $row['attributevalueEN']; ?></option>
<?php endforeach; ?>
</select>
<?php
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<a href="SearchResults.php?mushtype=<?php echo $row['idattributevalue']?>">Find Your Mushroom</a>
</form>
</body>
</html>
For the default selected option I want to use (*) as value because if no option are selected, will stand as SELECT (all) FROM for my SQL query on the second page. So, i tried to construct my hyperlink, but i don't know how to catch the selected option. I tried to adapt from here
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['Movies'])) {
$selected = $_POST['Movies'];
echo 'You have chosen: ' . $selected;
} else {
echo 'Please select the value.';
}
}
?>
but I'm unable to do it. Rigth now, my code inserting a value, but is without any control upon it.
Please help me to catch the selected option and insert it as value in my hyperlink. Thank you.
CodePudding user response:
When you use <a>, you do not submit the inputs to the next page. Instead of
<a href="SearchResults.php?mushtype=<?php echo $row['idattributevalue']?>">Find Your Mushroom</a>
simply use
<input type="submit" value="Find Your Mushroom">
before closing the form.
Edit:
Depending on the <form method=
you use ("get" or "post"), you will then either have $_GET['mushtype'] or $_POST['mushtype'] available in the next page. (Thanks to @ADyson!)
In my tests using method="get"
, the form inputs make their way to $_GET, but my uri parameters were not there. Using method="post"
gave me both my uri parameters in $_GET and form details in $_POST, just in case you want to use both.
If you do not like the button style however, you can change it using CSS to look just like a regular hyperlink.