MySql Dropdown filter select with NULL - mysql

I'm trying to build up a drop down filter system for a custom table. I have the following code but I can't seem to get it to work such that if one of the drops is not selected it still returns results based on the the selection of the second drop down:
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<select name="bt_nbs_intervention">
<option value=''>NbS intervention type</option>
<option value="3">Protection</option>
<option value="143">Restoration</option>
</select>
<select name="climate_change_impacts">
<option value=''>Climate change impacts</option>
<option value="15">Drought</option>
<option value="12">Flood</option>
<option value="25">Mangrove</option>
</select>
<input type='submit' value='Search'>
</form>
<?php
if ($_POST['bt_nbs_intervention'] === '') {
$_POST['bt_nbs_intervention'] = null;
}
if ($_POST['climate_change_impacts'] === '') {
$_POST['climate_change_impacts'] = null;
}
$bt_nbs_intervention = (int)$_POST['bt_nbs_intervention'];
$cc_impact = (int)$_POST['climate_change_impacts'];
$interventions = $wpdb->get_results($wpdb->prepare("
SELECT ID, intervention_post_title
FROM wp_cpt_combined
WHERE (bt_nbs_intervention IS NULL OR bt_nbs_intervention = %d) AND
(climate_change_impacts IS NULL OR climate_change_impacts = %d)",
$bt_nbs_intervention, $cc_impact));
if($interventions)
foreach ( $interventions as $intervention )
{
echo $intervention->intervention_post_title;
}
else {
echo "no results";
}
Essentially what I'm trying to do allow the user to select one or more of the select boxes to produce results. Such that if they only select Intervention type they get results or only Climate change impacts OR if they select both.
Hope that makes sense.
Thanks
D

Can you check the following please:
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<select name="bt_nbs_intervention">
<option value=''>NbS intervention type</option>
<option value="3">Protection</option>
<option value="143">Restoration</option>
</select>
<select name="climate_change_impacts">
<option value=''>Climate change impacts</option>
<option value="15">Drought</option>
<option value="12">Flood</option>
<option value="25">Mangrove</option>
</select>
<input type='submit' value='Search'>
</form>
<?php
$where = [];
$placeholders = [];
if(!empty($_POST['bt_nbs_intervention'])){
$where[] = 'bt_nbs_intervention = %d';
$placeholders[] = (int)$_POST['bt_nbs_intervention'];
}
if(!empty($_POST['climate_change_impacts'])){
$where[] = 'climate_change_impacts = %d';
$placeholders[] = (int)$_POST['climate_change_impacts'];
}
$sql = "SELECT ID, intervention_post_title FROM wp_cpt_combined";
if(!empty($where)){
$sql .= ' WHERE ';
$i = 0;
foreach($where as $clause){
$sql .= $i == 0 ? $clause : ' AND ' . $clause;
$i++;
}
$sql = $wpdb->prepare($sql, $placeholders);
}
$interventions = $wpdb->get_results($sql);

Related

How can I insert variable into SQL query only if it exist?

Let's say I have such html:
<form id="form">
Level:
<br/>
<select id="userLevel" name="userLevel">
<option value="">Choose level</option>
<option value="novice">novice</option>
<option value="intermediate">intermediate</option>
<option value="advanced">advanced</option>
</select>
Days per week:
<select id="days" name="days">
<option value="">Days per week:</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="button" id="btn" value="Submit"/>
</form>
<br />
<div id="txtHint"><b>Table goes here...</b></div>
Also I have a database with "user_level" and "days_per_week" columns. I want my code to show certain rows from that table, depends on wich parametrs user has chosen. But, if he didn't choose one of them, 'days' for example, program must display rows depending on only chosen parameters and dismising not chosen ones. How can I constuct SQL query properly? Something to check if that variable was set and if it wasn't - neglect it.
$userLevel = $_POST['userLevel'];
$days = $_POST['days'];
$sql="SELECT *
FROM table
WHERE ifset(user_level){
user_level = $userLevel
} else {
neglect this variable
}
AND ifset(days_per_week){
days_per_week= $days
} else {
neglect this variable
}"
EDIT: that table has about dozen of columns, and eventually that sql query will operate with several variables. I brought two of them just for example.
Here is your code :
$q = "";
if(isset($_POST['userLevel']) && $_POST['userLevel'] != "") {
$userLevel = $_POST['userLevel'];
$q .= " and user_level = '$userLevel'";
}
if(isset($_POST['days']) && $_POST['days'] != "") {
$days = $_POST['days'];
$q .= " and days_per_week= '$days'";
}
$sql="SELECT *
FROM table
WHERE id is not null $q"

html select dropdown wont stay selected

I have a select dropdown list on my website(www.irishbonus.comule.com/en/). However when I select an option from the dropdown list and press submit I would like that the option stay selected.
Here is the code for the select:
<form action="" method="post">
<strong> Select Subject:</strong>
<select name="formSubject" class="dropdown">
<option value=">>>">">>>"</option>
<option value="Accounting">Accounting</option>
<option value="Agricultural Science">Agricultural Science</option>
<option value="Agricultural Economics">Agricultural Economics</option>
<option value="Applied Mathematics">Applied Mathematics</option>
<option value="Arabic">Arabic</option>
<option value="Art (jc only)">Art (jc only)</option>
<option value="Biology">Biology</option>
<option value="Business (jc only)">Business (jc only)</option>
<option value="Business Studies">Business Studies</option>
<option value="Chemistry">Chemistry</option>
<option value="Civic (jc only)">Civic (jc only)</option>
<option value="Classical Studies">Classical Studies</option>
<option value="Construction Studies">Construction Studies</option>
//more options
<option value="Typewriting (jc only)">Typewriting (jc only)</option>
</select>
<table width="300px">
<tr>
<td valign="top">
<strong>Insert Mark:</strong>
<input type="text" name="formMark" maxlength="2" size="4" value="<?=$mark;?>"/>
</td>
</tr>
</table>
<input type="submit" />
</form>
You need to use a server-side language for this. You already seem to be using PHP so just add some PHP code to do it. The best solution would be storing your options inside an array and then iterating over the array, outputting the <option> tags and adding the selected attribute if the value matches the submitted value.
<select name="formSubject" class="dropdown">
<?php
$options = ['Accounting', 'Agricultural Science', '...'];
$selected = isset($_POST['formSubject']) ? $_POST['formSubject'] : '';
foreach($options as $option) {
echo '<option value="'.$option.'"'.($selected == $option ? ' selected' : '').'>'.$option.'</option>';
}
?>
</select>
He forgot the array(), that is why the parse error is there
here:
<select name="formSubject" class="dropdown">
<?php
$options = array('Accounting', 'Agricultural Science', '...');
$selected = isset($_POST['formSubject']) ? $_POST['formSubject'] : '';
foreach($options as $option) {
echo '<option value="'.$option.'"'.($selected == $option ? ' selected' : '').'>'.$option.'</option>';
}
?>
</select>
while ($row = $result->fetch_assoc()) {
$selected = "";
if(isset($_GET['spec'])) {
if($_GET['spec'] == $row['id']) {
$selected = "selected='selected'";
}
}
print "<option ". $selected ." value='". $row['id'] ."'>". $row['ime']. "</option>";
}
$result->free();

Selecting Data from select tag

i have to select data from select tag rather then selecting value as its selects value for default
<select name="time" >
<option selected="selected" >timings</option>
<option value="155">9:00AM - 12:00PM</option>
<option value="244">12:00AM - 15:00PM</option>
</select>
I want to select 12:00AM - 15:00PM values and store it in my DB. How to do it any ideas.
Thanks in advance
Ameeth
<select name="time">
<option selected="selected" >timings</option>
<option value="9:00AM - 12:00PM">9:00AM - 12:00PM</option>
<option value="12:00AM - 15:00PM">12:00AM - 15:00PM</option>
</select>
<?php
$value = $_POST["time"]; //what method you are using
?>
or
<select name="time" >
<option selected="selected" >timings</option>
<option value="155">9:00AM - 12:00PM</option>
<option value="244">12:00AM - 15:00PM</option>
</select>
<?php
$value = "";
switch($_POST['time']){
case '155':
$value="9:00AM - 12:00PM";
break;
case '244':
$value = "12:00AM - 15:00PM";
break;
default:
$value = "No data found";
break;
}
?>
You've two options;
Use 12:00AM - 15:00PM inside the value="" parameter.
OR
Do something like this in PHP file for collecting data and inserting it into db;
if ($_POST['time'] == "155")
{
$time = '9:00AM - 12:00PM';
}
elseif ($_POST['time'] == "244")
{
$time = '12:00AM - 15:00PM';
}
// do rest of the data insertion into db

MySQL select query with ajax in wordpress

I am passing variable with ajax to list.php in my twentytwelve template. In list.php I am executing mysql select query but when I see in console I am getting this error:
<br />
<b>Fatal error</b>: Call to a member function get_results() on a non-object in <b>D:\xampp\htdocs\wordpress\wp-content\themes\twentytwelve\list.php</b> on line <b>4</b><br />
My Code:
search.php
<?php
/*
Template Name: Search
*/
get_header();?>
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#parent_category").change(function()
{
var parent_category = $(this).val();
if(parent_category != '')
{
$.ajax
({
type: "POST",
url: "<?php echo get_template_directory_uri(); ?>/list.php",
data: "parent_category="+ parent_category,
success: function(option)
{
$("#child_category").html(option);
}
});
}
else
{
$("#child_category").html("<option value=''>-- No category selected --</option>");
}
return false;
});
});
</script>
<select id="parent_category" name="parent_category">
<option value="" selected="selected">-- Select blood group --</option>
<option value="A1 positive">A1 positive</option>
<option value="A1 negative">A1 negative</option>
<option value="A2 positive">A2 positive</option>
<option value="A2 negative">A2 negative</option>
<option value="B positive">B positive</option>
<option value="B negative">B negative</option>
<option value="A1B positive">A1B positive</option>
<option value="A1B negative">A1B negative</option>
<option value="A2B positive">A2B positive</option>
<option value="A2B negative">A2B negative</option>
<option value="AB positive">AB positive</option>
<option value="AB negative">AB negative</option>
<option value="O positive">O positive</option>
<option value="O negative">O negative</option>
<option value="A positive">A positive</option>
<option value="A negative">A negative</option>
</select>
<select id="child_category" name="child_category">
<option value="">-- No location selected --</option>
</select>
<?php get_footer(); ?>
list.php
<?php
if(isset($_POST['parent_category']) && $_POST['parent_category'] != '')
{
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
print_r($result);
}
?>
Any ideas or suggestions? Thanks.
you have to include the wp-blog-header in your list.php then define $wpdb as global the error you are is due to the definition of $wpdb which is undefined
<?php include("yourpath/wp-blog-header.php");
global $wpdb;
if(isset($_POST['parent_category']) && $_POST['parent_category'] != '')
{
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
print_r($result);
}
?>

Multiple options for query from select menu

I have a search area which contains 3 field, one is an input field and the other two are drop down menus. Either someone enters something into the input field or they select from BOTH of the drop downs (state and city).
Input search works fine. Select menus do not.
Here is the form.
<form name="ffl_finder" method="get" action="index.php">
Enter a Zip Code to find a Firearms Dealer near you: <br />
<input name="q" type="text" id="q" size="40">
Select a State AND a City<br />
<select name="qoption2">
<option value="" selected="selected">Select . . .</option>
<?php
$sql2 = "SELECT DISTINCT state from ffl_list order by state asc";
$rs_results2 = mysql_query($sql2) or die(mysql_error());
while ($rrows2 = mysql_fetch_array($rs_results2)) {
?>
<option value="<?php echo $rrows2[state]; ?>"><?php echo $rrows2[state]; ?></option>
<?php
}
?>
</select>
<select name="qoption3">
<option value="" selected="selected">Select . . .</option>
<?php
$sql3 = "SELECT DISTINCT city from ffl_list order by city asc";
$rs_results3 = mysql_query($sql3) or die(mysql_error());
while ($rrows3 = mysql_fetch_array($rs_results3)) {
?>
<option value="<?php echo $rrows3[city]; ?>"><?php echo $rrows3[city]; ?></option>
<?php
}
?>
</select>
<input name="doSearch" type="submit" id="doSearch" value="Search">
</form>
Here is the query:
<?php if ($get['doSearch'] == 'Search') {
//$cond2 = '';
if($get['qoption2'] != '') {
$cond2 = "`state` = 'qoption2'";
}
//$cond3 = '';
if($get['qoption3'] != '') {
$cond3 = "`city` = 'qoption3'";
}
if($get['q'] == '') {
$sql = "select * from ffl_list where $cond2 and $cond3 order by state asc, city asc";
}
else {
$sql = "select * from ffl_list where `zip` = '$_REQUEST[q]' ORDER BY `id` asc";
}
$rs_results = mysql_query($sql) or die(mysql_error());
} ?>
I need the query to search both city and state and I cannot seem to get the conditions right. I know this is a lot of code but if someone could help that would be great.
Thanks,
Clint
<?php
while ($rrows2 = mysql_fetch_array($rs_results2))
{
?>
<option value="<?php echo $rrows2['state']; ?>"><?php echo $rrows2['state']; ?></option>
<?php
}
?>
state and citymay be cols' names of the ffl_list table, you have to use a string a key of the returned array from mysql_Fetch_array. You did wrong for $rrows2 and $rrows3
When you create your filter for the query, you set a hard string, not GETted data :
$cond2 = '';
if($_GET['qoption2'] != '') {
$cond2 = "`state` = '".$_GET['qoption2']."'";
}