Setting A $_GET Value From A Previously Defined Variable - PHP
I have a search form in the header of every page on a site that submits info to another page when undertaking a search query via the form's action
attribute, namely a page called search.php
and it takes the value of the search <input>
field and stores it as a variable called searchQuery
. Using PHP this searches a MySQL database. All of this works as expected.
I would like the value of the search input field to be placed in the URL of the page the search is processed on, again namely search.php
.
I understand from other questions on SO that you can't add variables to a form's action
attribute. If I add the key of the query string in the action attribute, the form still works OK:
action="search.php?keyword="
From this I thought I would be able to then set the $_GET
value on the search.php
page by using:
if(isset($_POST['search-submit'])) {
// make this variable available before HTML output
$searchQuery = htmlspecialchars($_POST['search']);
$_GET['keyword'] = $searchQuery;
}
This however does not work, although it doesn't throw any errors in my PHP error logs.
Because I'm running the script on specific page allocated by the action attribute, I don't think I need to use a $_SESSION
variable?
HTML Form
Here is the form that is on every page in the header
<form action="search.php?keyword=" method="POST">
<label for="search">Enter Search</label>
<input type="search" name="search" id="search">
<button type="submit" name="search-submit" id="search-submit">Search</button>
</form>
1 answer
-
answered 2022-05-07 17:41
The Chewy
In your form set the method to
GET
, remove the query string from theaction
attribute so it is justsearch.php
, change the name on the search input field tokeyword
and remove thename
on thesubmit
button.<form action="search.php" method="GET"> <label for="search">Enter Search</label> <input type="search" name="keyword" id="search"> <button type="submit" id="search-submit">Search</button> </form>
Then in your
search.php
page, change your initial code to the following:if(isset($_GET['keyword'])) { // make this variable available before HTML output $searchQuery = htmlspecialchars($_GET['keyword']); } else { header("Location: index.php"); // use whatever page is your home page or preferred page to redirect to }
And then in your search query make sure the
$_GET
value is set:if(isset($_GET['keyword'])) { // run your search query using the $searchQuery variable }
do you know?
how many words do you know