John Davidson

php - Posting result in mysql WHERE statement from form ($_GET) when no selection is made by a user

0 comments
Message:


Sorry if this has been asked before, I searched but couldn't find a suitable answer. There is probably a simple answer for this, but I'm stumped and hoping someone can provide a quick answer. I've got a form on my site where users can filter the data multiple ways. One filtering option in the the form is 'intensity' (low, medium, high). I'm using $_GET variables to post in the mysql WHERE statement. It works fine when an intensity option is chosen, but when the user does not choose an option I get no results output. What can I use as a value in the form that will end up outputting all intensities in the WHERE statement.


Below are snippets of the code...


<form action="workouts.php" method="GET" style="margin-top:5px">
<small>intensity</small>
<select id="intensity" name="intensity">
<option value="" selected="selected"></option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
<option value="auto">Auto</option>
</select>
<small> <input type="submit" value="go" style="font-size:12px"/></small>
</form>

<?php $intensity = $_GET['intensity']; ?>




This is the WHERE statement I'm calling $intensity in...


SELECT * FROM data WHERE complete = '1' and intensity = '$intensity' ORDER by date DESC



My Answer:
You can use a conditional statement to check if the intensity option is selected or not. If it is not selected, you can set the intensity value in the WHERE statement to include all intensities. Here's an example of how you can modify your code:

php
$intensity = isset($_GET['intensity']) ? $_GET['intensity'] : '';

// Check if intensity is selected
if ($intensity == '') {
$intensity_condition = "IN ('low', 'medium', 'high')";
} else {
$intensity_condition = "= '$intensity'";
}

// Use $intensity_condition in your WHERE statement
$query = "SELECT * FROM your_table WHERE intensity $intensity_condition";


This way, if the user does not select an intensity option, the WHERE statement will include all intensities ('low', 'medium', 'high'). If an intensity option is selected, it will only include that specific intensity in the WHERE statement.

Rate this post

3 of 5 based on 4257 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us