开发者

Drop down Selection -> Search database

How would I search an SQL database when a user makes a selection in a dropdown list. I know how to change/add text to areas using some javascript but not with a SQL search as well.

Ideally开发者_如何学运维 I don't want to be changing pages in this process as I'm thinking they won't be sticking on a single option in the drop down for long.

Cheers in advance. =)


You have to add an onchange event listener to the dropdown box. When the user selects an option, an AJAX (XmlHttpRequest) should be send to the server. A serverside script, a PHP page for example, should parse the parameters (after checking).

When these parameters have been checked, they should be escaped for this reason. Perform a search query, parse the results, and send the output back to the client (the user, browser).

Useful links:

  • http://www.php.net/manual/en/ref.mysql.php
  • https://developer.mozilla.org/en/xmlhttprequest


you should look into implementing Ajax for this.

Here's a simple example and tutorial utilizing a drop down list that fetches information from a database on selection, without changing pages :)

http://www.w3schools.com/php/php_ajax_database.asp

You should also look into using jquery for your Ajax requests as stated in the answer below. (Do more with less code).

See also: http://15daysofjquery.com/quick-and-dirty-ajax/14/ for a simple jquery Ajax tutorial.


Before you render the page, make sure you do a grab the info you want presented from the database.

select distinct NAME, ID
from   tableName

You can use the information obtained here to generate the html for a drop down box. Include something to the effect

<select onchange="doAction(this.value);">
  <option value="userID">userName</option>
  <option value="userID">userName</option>
  <option value="userID">userName</option>
  ...
</select>

Then perform an AJAX request back to your site. Get your information from your second query to the database, and return with the information you need. When you perform your second query (and in general) you have to protect yourself against injection attack vectors. The best start for this is to make sure you have encoded(HTML, SQL) correctly.


Without more information I can only really give you the below as a guide. It uses the jQuery load function to put the contents of one page into an element. Note that .load cannot be used across domains.

$("#searchButton").live("click", function() {
    $("#results").load("/SearchResults.php?s=" + $("#searchBox").val());
});

Also note that you should use something to filter out HTML tags to prevent SQL injection, as well as taking other measures.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜