0

I'm having some difficulties with the php form concept which is as follows:

There is a keyword search input form on a site which is meant to refine the appearance of the images on the site. The idea is that the keywords are passed using the get method which constructs the url as such:

  • page.php?keyword=tree

The database query is built in such a way that it can handle multiple keywords which would appear in the url as comma-separated keywords:

  • page.php?keyword=tree,green,oak

How would I build a submit form which will allow users to enter a keyword which will output this page.php?keyword=tree and if he inputs another keyword in the input field it will change the link to

  • page.php?keyword=tree,green

adding another keyword at its end?

My original idea was to retrieve the current url and deliver a custom one in case a variable already exists, but I'm not sure how the form itself should handle the action.

Any help will be appreciated

Don
  • 863
  • 1
  • 8
  • 22
jacek_podwysocki
  • 807
  • 10
  • 30

2 Answers2

0

What you're trying to do can be accomplished with a hidden <input> and some javascript combined with minimal PHP.

Your form would look like this:

<form id="myForm" action="">
    <input type="hidden" id="keyword" name="keyword" value="<?= $_GET['keyword'] ?>" />
    <input type="text" id="newKeyword" name="newKeyword" /><br />
    <input id="submit" type="submit" />
</form>

Then with jQuery, you could modify the submit button's behavior:

<script language="javascript" type="text/javascript">
    $("#submit).on('click', function() {
        var keyword = $("#keyword").val();
        var newKeyword = $("#newKeyword).val();

        if (keyword != "") {
            keyword = keyword + ",";
        }
        keyword = keyword + newKeyword;

        window.location.href = "?keyword=" + keyword;
    });
</script>

Keep in mind that when you're accessing your database you should not use mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this SO article.

Community
  • 1
  • 1
Matt
  • 6,993
  • 4
  • 29
  • 50
  • This solution seems to be quite solid, yet it does not return what expected. On the first search the keyword is not set so GET is empty. Therefore it returns ?keyword=&newKeyword=test That must be some small modification that I will try too figure out... – jacek_podwysocki Aug 03 '12 at 20:48
  • After correcting some typo mistakes from your solution and adding onSubmit="return false" to the form, everything works great. Thank you! – jacek_podwysocki Aug 03 '12 at 21:21
0

You could even solve this on the server side by using multiple input tags all with name attribute = keywords[].

PHP will create a nice array out of it: $_REQUEST['keywords']. Take it and e.g. implode.

Just ask in case I'm not totally clear...

Lars Knickrehm
  • 739
  • 4
  • 14