Implementing Form that Might Result in Different Queries - php

I have a form that needs to allow people to search for hikes, hiking groups, or hikers, depending on what radio button they choose within the form.
Obviously, in either of these 3 cases, the query will be of different tables in the database, and have different usability down the road. So I probably shouldn't process all of these in one place I am assuming. Would you guys agree?
What might be a good practice way to handle such a case? I tried redirecting the request to single form processing modules, but I had trouble making a POST request in the URL that I was trying to redirect.
Ideas/suggestions appreciated,
Alex

I don't see a problem handling this from 1 form. pass on the search type and build an appropriate query based on the type, search terms, etc. Even if the queries are totally different, it sounds like the input your gathering is pretty simple. You may want to display the results with different pages, but processing can easily be handled with one form and one script.
Quick example:
//get variables out of POST
if ($search_type == "hike")
{
//put together a hike query, get results
//call script to display hikes
}
elseif ($search_type == "group")
{
//put together a group query, get results
//call script to display hikes
}
elseif(...) //etc, etc

You can just check the value for the radio button and call different methods for further handling the form. That way you can put the queries and any related code in totally different files.
Where exactly do you see a problem in that? In how is the handling behind the screens related to user-experience?

Related

Build generic PHP/MySQL query based on data filters set in HTML

I'm trying to find the best way to make "filtering" of my data. Filters are set by input fields on front end, and based on that filters (inputs) i need to build query in PHP and retrieve data from MySQL database.
This would be easy if i had only one page and one query where i filter data, but i have more pages which pull data from everywhere around database.
What i have in my mind is to build front end HTML forms, with inputs corresponding to database fields, and then when i get form posted, to go via
if(some_field != '')
$q .= ' AND some_field = some_field_value';
problem is i have some fields which should be compared with LIKE and it only gets more complex introducing more fields and values..
I'm sure that there must be better approach to this problem.
I wonder, is there any good example of best practise to similar data filtering?
What I understand is that you have different pages that you want your backend to cater to? And that some of these pages have similar fields but possible to have two pages with different need of query statement(= vs LIKE)? You may include a hidden field that you check in the php code if it needs to use the query statement with LIKE. It will really be complex since you are trying to cater to varying situations and filter fields.
What I did to my filtering is tackle it one filter for each entity...so for example, I have customer module, it has different filter to Purchase Order module...

Generate an Output Based on Form Options

I've searched this relentlessly and I cannot find an answer to my quandary - I think the problem is that I'm not exactly sure WHAT to search for! Anyhow, my problem is this...
Scenario:
Imagine having a database of, for arguments sake, recipes and you wanted to give users the ability to generate a list of recipe suggestions based on various criteria.
In the form of a web page, I would want this to be a series of drop down boxes on the left. The user would select their filter options from the drop down boxes and, after pressing the submit button, would be presented with a list of recipes that fit the criteria.
So they could, for example select 'Meal Type', 'Calories', 'Cooking Time' and then (after hitting submit) get back a list of recipe suggestions that fit the bill.
(Ideally they would appear without the need for reloading the page and would be contained within a slider to browse through, but I can probably crack that part if I get the underlying part sorted...)
Requirement:
I just need to know - at a top level - which technologies I would use to achieve this (and the process of how they work together).
I'm guessing I'd need a MySQL dB with recipes that are tagged with criteria, then use the form and php to pull from the database. Is this correct?!
Seems like such a common requirement, but I can find no good reading on how to achieve this..
Take a look at the PHP guide to prepared statements. You'll be basically writing a select statement against the table where your data resides, with the where clause of the select statement being the parameters selected by your user in the form.
PHP Prepared Statements
The reason you want to stick to prepared statements is that they are generally more secure against attacks on your site via the form, using SQL injection.
For the end to end solution, your front end will submit to a PHP page which will then handle the criteria specified by the user, translating those into the prepared statement which will find the data from your table. The table itself will need to have columns which correspond to the criteria. That gets more into database design which is a much larger topic to cover here, however there are plenty of guides out there for that.
Really you want to break the solution down into the subcomponents, then find various guides out there to tackle the parts. Good luck, hope this helps. :)
The process:
1) User makes selection and clicks submit button. That will initiate a HTTP POST to a PHP page (can be the same PHP page) where you would collect these information.
2) Open a MySql database connection with PHP. You would need to know SQL to pull data from MySql DB. Depending on how your database schema is laid out.
3) Once you pull this information display them as a checkbox where user can click.
This is the bare minimum.
If you wanna get a bit more fancy you can use JQuery ajax post (http://api.jquery.com/jQuery.post/) so the page does not refresh.
Good luck and I'm already hungry. haha.
When the user selects options in your form and submits it, this will run a PHP script on the server. The server retrieves the option parameters, and uses them to construct a SQL query. For instance, the script might contain something like:
$criteria = array();
if (isset($_POST['calories'])) {
$criteria[] = 'calories < '.$_POST['calories']);
}
if (isset($_POST['time'])) {
$criteria[] = 'cooking_time < '.$_POST['time']);
}
...
$query = 'SELECT * FROM recipes WHERE '.implode(' AND ', $criteria);
You use a library like mysqli or PDO to perform the query and get the results. Then you loop through the results, and format them into an HTML table which will be returned to the user as the resulting web page.
Or the PHP script could return the results as JSON data. Your web page could use AJAX to get this data from the server, then use JavaScript to format it into a table.

Best way to create a dropdown filter?

I've been trying to filter information to make it easy for a visitor to find. Ideally I would have a few dropdown filters to sort the data and only the posts matching the options selected would be shown. I have hardly a clue as to how this is done, except through php. I found a nice example of what I'm trying to do right here:
http://www.darienps.org/dhs/courses.php
Any ideas?
Have you looked into AJAX? Using some JavaScript (perhaps a library of your choosing), you would make what are called AJAX calls to some server-side logic (probably to query the database) to return the desired data. If you're not familiar with this, I can tell you more.
I'm not sure if this is really what you want to know, but assuming you'd construct a database query to do the search, you'd have to test in your PHP each parameter of the form (each dropdown), if it is set or not.
If it is set, you'd just add a restriction in your database query (in the WHERE clause).
This would return the results matching the parameters selected by the user.

PHP & MySQL - Making a Filterable Search (example provided)

I'm putting together a practice site utilizing PHP and MySQL to replicate (or closely resemble) this site. As of right now my searchable fields include: Rent (min-max), Type of rental (any, apartment, house), Number of Bedrooms (any, 1+, 2+, 3+, 4+)
I'm not having trouble with putting together the code thus far, I'm just worried about scaling issues and want to know what is considered best practice. Also, any advice for how to replicate the 'Sidebar filter search' that is on the site I linked (eBay also has something very similar) would be awesome.
Here is where I've hit a fork in the road: Do I individually process each field filter in a MySQL query or do I call all items in a table and then filter them in PHP?
$sql = "SELECT * FROM properties ";
$properties = Property::find_by_sql($sql);
$matched_properties = array();
foreach($properties as $property):
if ($min_rent <= $property->rent && $property->rent <= $max_rent) {
$matched_properties[] = $property;
}
endforeach;
The code above pulls everything from 'properties' table in MySQL and makes a Property classes (basic CRUD class) array.
Apologies if I sound jumbled, but my main question is How can I replicate a filtered search such as that on this site OR eBay.com? And am I on the right path?
Thank you
Generally speaking, the less data you have to pull from your database to process in PHP, the better. Less code you have to write, less resulting bugs, less data to transfer through the software stack, etc. etc. You may need to read up on how to write more complex SQL queries. The following would be a much more efficient version of the code snippet you gave:
$sql = "SELECT * FROM properties WHERE rent >= $min_rent AND rent <= $max_rent";
$matched_properties = Property::find_by_sql($sql);
For security though, you'd need to make sure $min_rent and $max_rent are validated as real numbers. (Hint: pass the inputs through is_numeric() and throw an error if this function returns false.) Otherwise a hacker could perform what's known as a Code Injection, entering other snippets of SQL query strings in place of "min_rent" or "max_rent" to make your query do lots of undesirable things.
As for implementing a filtering mechanism like that U of Iowa site, it's a matter of having links or a form in the sidebar that refreshes the page when clicked. You can do this several ways. The coolest way is probably using AJAX to automatically update the main content window. The U of Iowa site doesn't seem to be doing this, because when I click various filter links in the sidebar, the entire page refreshes instead of just the main content area.
jQuery is a really helpful JavaScript library that can help you do AJAX with minimal coding. Check it out. Basically, you'll want to build your filter sidebar so that each link clicked causes an AJAX query to your server, which pulls in an updated data set based on the user's selected filters. When the result comes back from the AJAX call, you can use JavaScript and/or jQuery methods to inject the data as needed into your page.
Good luck!

Thousands of items in multiple dropdown menus

A client has given me a task to do that I've not done before, and so I'm looking for the best way to do it. They have a form they want users to fill in, but for one field, they want an option of thousands to be placed into three dropdown menus.
For example:
So a user will only be able to choose a Venue once they've chosen a City, only a City once they'd chosen a State. (A nice way to break up the thousands of options.)
I suppose I could this quite easily using POSTBACKs and a simple database, but I imagine that doing something with AJAX and a simple database would be the slicker solution.
Are there any other ways that this problem might be tackled? If not, does anyone have any links to tutorials or code snippets I could grab? Secondly, how long do you think it would take you to implement such a system?
I've never done this before so I'm hoping to avoid as many unforeseen pitfalls as possible. Thanks.
How about a simple jQuery Autocomplete solution?
I've done such a thing, also with several thousands of entries.
The problems:
it's difficult for the end user to navigate trough the list if there are hundreds of cities to choose
dropdowns as they are terrible for such things
querying a database to obtain info is stressful because the query is basically the same, with same results, nearly never-changing.
So on to solutions:
I still stood by dropdowns, but I added (trough UI) options for users to filter the list a bit. I won't post the code or the layout, if you are fine with the dropdowns as they are - keep them.
I loaded all of the countries, cities and areas via JS once. Now, why - first off, it wasn't that huge of a deal, it was about 20ish kilobytes gzipped if I'm not mistaken. I didn't want the "please choose a country" > "please wait, loading cities" > "choose a city" > "please wait, loading areas" > "choose an area" thing, I absolutely hate waiting so I don't want anyone to wait if they don't have to :)
So, the whole structure is loaded at once (when page is requested) and kept inside an object. If the browser supports sessionStorage, I check whether I have the object there in the first place - if not, I load it via jQuery's $.ajax call.
On the web server, the script returning JSON object actually loads the data from Memcache. If there's no entry in the Memcache, then I query the db and load all the data and I store it with Memcache for later use.
Now, what happens is that I've got a JS object representing all countries, cities and areas - with relations, meaning I can render the dropdowns in any way I need to, showing only relevant cities for current country selection.
Now, as you have similar structure - you can apply the same logic.
Load the item when the page loads, but check if you have sessionStorage available. If yes, check if you got object there. No? Do a $.ajax call and obtain it. When dropdowns fire change event, render the appropriate data.
Hopefully this helps a little, I'm typing this in a rush :)
A few responses:
This is a good use of AJAX, no need to look for another method. You wouldn't want to force the client to pre-load all of the javascript arrays for the possible state/city/theater combinations...
jQuery Autocomplete is a good tool to use to implement the UI
The list of cities and states can be obtained from GeoNames
How long it would take to implement depends on the skill of the implementer ;)
Somewhat working example: http://jsfiddle.net/rA9gU/36/
Hope this might help
UPDATE: Added the NO theater found near you option
http://jsfiddle.net/rA9gU/39/
You've got it. On the "on change" event for each dropdown, run an AJAX request for the options for the next dropdown.
With jQuery it's pretty simple.
$(document).ready(function () {
$("#state").change(function () {
// AJAX call w/ $.get or $.post to a script to return and set city options
});
// Same for city to retrieve cinema options
....
});
jQuery is by no means a requirement -- just wraps things up nicely and in cross-browser fashion.
Be happy to provide a more specific example if you like.

Categories