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

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"

Related

Multi forms with selects but all $_POST are overwritten with last $_POST

In below test code I try to save and use 3 $_POST variables. But only the last $_POST variable is stored. The rest is overwritten with the last $_POST variable.
Purpose of the question is to select first the wanted country. Select from a table the country as selected. Then select the wanted a car_brand from the selected country. Then select the wanted company and filter this from the selected country+car_brand.
I have tried to store the 3 $_POST into a $_SESSION also tried it with $_REQUEST via type="hidden" without getting the 3 $_POST variables.
Question: what do I do wrong and how can I solve this problem?
session_start();
$content .= ' <form id="sel_country" method="POST">
<select name="country" onchange="this.form.submit()" >
<option value="NL">Netherlands</option>
<option value="DE">German</option>
<option value="GB">England</option>
</select>
</form>';
$content .= '<form id="sel_car_brand" method="POST">
<select name="brand" onchange="this.form.submit()" >
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="audi">Audi</option>
</select>
</form>';
$content .= ' <form id="sel_company" method="POST">
<select name="company" onchange="this.form.submit()">
<option value="dealer">Dealer</option>
<option value="service">Service</option>
<option value="import">Importer</option>
</select>
</form>';
$_SESSION['country'] = $_POST['country'];
$_SESSION['brand'] = $_POST['brand'];
$_SESSION['company'] = $_POST['company'];
var_dump($_SESSION) ;
Had a session_start() at the beginning and then stock your variable in it. Like $_SESSION['country'] = $_POST['country'] when $_POST['country'] is defined (do a var_dump() to verify it) and you'll be able to access your datas stocked in your $_SESSION.
session_start();
$content .= ' <form id="sel_country" method="POST">
<select name="country" onchange="this.form.submit()" >
<option value="NL">Netherlands</option>
<option value="DE">German</option>
<option value="GB">England</option>
</select>
</form>';
$_SESSION['country'] = $_POST['country'];
$content .= '<form id="sel_car_brand" method="POST">
<select name="brand" onchange="this.form.submit()" >
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="audi">Audi</option>
</select>
</form>';
$_SESSION['brand'] = $_POST['brand'];
$content .= ' <form id="sel_company" method="POST">
<select name="company" onchange="this.form.submit()">
<option value="dealer">Dealer</option>
<option value="service">Service</option>
<option value="import">Importer</option>
</select>
</form>';
$_SESSION['company'] = $_POST['company'];
var_dump($_SESSION) ;
// Edited by moliets: var_dump response: array(3) { ["country"]=> NULL ["brand"]=> NULL ["company"]=> string(6) "import" }

Select item from HtmlSelect that contains some string

I have select. As you might see, text is different from value.
<select id="divPlatformsPopup" ClientIDMode="Static" runat="server" class="selectpicker col-md-12 ClassPad0" multiple title='Choose one of the following...' data-container="body" data-selected-text-format="count>2" data-style="btn-xs btn-default">
<option value="All">All Platforms</option>
<option value="Mobile Phone,Tablet,Windows Phone,PlayStation Certified Device,Windows 8 App,PlayStation Mobile">Mobile App/Tablet</option>
<option value="Nintendo DS,Nintendo DSi,Nintendo 3DS">Nintendo DS/DSi/3DS</option>
<option value="Playstation 3">Playstation 3</option>
<option value="PlayStation 4">PlayStation 4</option>
<option value="PSP,PS Vita">PlayStation Vita/PSP</option>
<option value="Wii">Wii</option>
<option value="Wii U">Wii U</option>
<option value="Linux,Macintosh,PC DVD,PC DVD-ROM,Windows CE,Windows PC,Windows 8 App">Windows/Mac</option>
<option value="Xbox 360">Xbox 360</option>
<option value="Xbox One">Xbox One</option>
<option value="3DO,Atari Jaguar,Atari Lynx,Cable Box,CDI,Dreamcast,DVD,Game Boy,Game Boy Advance,Game Boy Color,Game Gear,Game Wave(Custom DVD gaming platform),Game Cube,Gizmondo,Hyperscan,iPod,N-Gage,Neo Geo Pocket Color,Nintendo,Nintendo 64,Nintendo Game Boy,NUON,Online,Other,Palm Pilot,PDA(Palm, Win CE, etc.),PlayStation&2FPS one,Playstation 2,Plug-and-Play,Pocket Arcade,Pocket PC,Pokemon Mini,Sega 32x,Sega CD,Sega Dreamcast,Sega Genesis,Sega Pico,Sega Pocket Arcade,Sega Saturn,Super Nintendo,VG Pocket,Virtual Boy,Web Browser,Web Site,Web TV,Xbox,Zodiac,Firefox">Other Platforms</option>
</select>
And I have part of code to set selected values by value.
foreach (var li in platforms.Select(platform => divPlatformsPopup.Items.FindByValue(platform)))
{
li.Selected = true;
}
where platforms is list of selected values
But here is one case that i didn't count. It's possible to pass into platforms list value which is part of value from select (For example "Nintendo DS" as part of "Nintendo DS,Nintendo DSi,Nintendo 3DS").
And i want to know how to select item which contains some part of VALUE of select item.
Well, i find solution:
I goes in a loop for every item in Select and check if item contains some string
foreach (var platform in platforms)
{
for (var i = 0; i <= divPlatformsPopup.Items.Count; i++)
{
if (Array.IndexOf(divPlatformsPopup.Items[i].Value.Split(','), platform) > -1)
{
divPlatformsPopup.Items[i].Selected = true;
}
}
}

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

HTML select <option> returns only the first letter of selected option

I have a code somewhat like this
<?php
if($_POST['post'] == 'Post')
{
$cat = $_POST['cat'];
$update = "UPDATE table SET category='$cat' WHERE id = '$id' ";
$result = mysql_query($update) or die ("update error");
}
?>
<form action="#" method="post">
<select name="cat">
<option >Arts and Entertainment</option>
<option >Automotive</option>
<option >Book Reviews</option>
<option >Business</option>
<option >Communications</option>
<option >Computers and Technology</option>
<option >Finance</option>
</select>
<input type="submit" name="post" value="Post">
</form>
I summarized my code for you to get it easily,
whatever I select on my option,
only the First letter of the option comes out.
Your code seems ok on both PHP and HTML side.
So you might have store your value on category with its fieldtype varchar(1) or char(1).
If that is the case increase your char or varchar length to let say 50.

Can an Option in a Select tag carry multiple values?

I got a select tag with some options in a HTML form:
(the data will be collected and processed using PHP)
Testing:
<select name="Testing">
<option value="1"> One
<option value="2"> Two
<option value="3"> Three
</select>
Is it possible for an option to carry multiple values like when a user selects
"One", then a few other values related to this option will be written to the Database.
How should I design the select Tag so that each of the options can carry one than one value like this:
<select name="Testing">
<option value="1" value="2010"> One
<option value="2" value="2122"> Two
<option value="3" value="0"> Three
</select>
One way to do this, first one an array, 2nd an object:
<select name="">
<option value='{"num_sequence":[0,1,2,3]}'>Option one</option>
<option value='{"foo":"bar","one":"two"}'>Option two</option>
</select>
I achieved it by using the PHP explode function, like this:
HTML Form (in a file I named 'doublevalue.php':
<form name="car_form" method="post" action="doublevalue_action.php">
<select name="car" id="car">
<option value="">Select Car</option>
<option value="BMW|Red">Red BMW</option>
<option value="Mercedes|Black">Black Mercedes</option>
</select>
<input type="submit" name="submit" id="submit" value="submit">
</form>
PHP action (in a file I named doublevalue_action.php)
<?php
$result = $_POST['car'];
$result_explode = explode('|', $result);
echo "Model: ". $result_explode[0]."<br />";
echo "Colour: ". $result_explode[1]."<br />";
?>
As you can see in the first piece of code, we're creating a standard HTML select box, with 2 options. Each option has 1 value, which has a separator (in this instance, '|') to split the values (in this case, model, and colour).
On the action page, I'm exploding the results into an array, then calling each one. As you can see, I've separated, and labelled them so you can see the effect this is causing.
its possible to have multiple values in a select option as shown below.
<select id="ddlEmployee" class="form-control">
<option value="">-- Select --</option>
<option value="1" data-city="Washington" data-doj="20-06-2011">John</option>
<option value="2" data-city="California" data-doj="10-05-2015">Clif</option>
<option value="3" data-city="Delhi" data-doj="01-01-2008">Alexander</option>
</select>
you can get selected value on change event using jquery as shown below.
$("#ddlEmployee").change(function () {
alert($(this).find(':selected').data('city'));
});
You can find more details in this LINK
one option is to put multi value with comma seperated
like
value ="123,1234"
and in the server side separate them
When I need to do this, I make the other values data-values and then use js to assign them to a hidden input
<select id=select>
<option value=1 data-othervalue=2 data-someothervalue=3>
//...
</select>
<input type=hidden name=otherValue id=otherValue />
<input type=hidden name=someOtherValue id=someOtherValue />
<script>
$('#select').change(function () {
var otherValue=$(this).find('option:selected').attr('data-othervalue');
var someOtherValue=$(this).find('option:selected').attr('data-someothervalue');
$('#otherValue').val(otherValue);
$('#someOtherValue').val(someOtherValue);
});
</script>
What about html data attributes?
That's the easiest way.
Reference from w3school
In your case
$('select').on('change', function() {
alert('value a is:' + $("select option:selected").data('valuea') +
'\nvalue b is:' + $("select option:selected").data('valueb')
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<select name="Testing">
<option value="1" data-valuea="2010" data-valueb="2011"> One
<option value="2" data-valuea="2122" data-valueb="2123"> Two
<option value="3" data-valuea="0" data-valueb="1"> Three
</select>
In HTML:
<SELECT NAME="Testing" id="Testing">
<OPTION VALUE="1,2010"> One
<OPTION VALUE="2,2122"> Two
<OPTION VALUE="3,0"> Three
</SELECT>
For JS:
var valueOne= $('#Testing').val().split(',')[0];
var valueTwo =$('#Testing').val().split(',')[1];
console.log(valueOne); //output 1
console.log(valueTwo); //output 2010
For PHP:
$selectedValue= explode(',', $value);
$valueOne= $exploded_value[0]; //output 1
$valueTwo= $exploded_value[1]; //output 2010
I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.
HTML
<select class="example">
<option value="1" data-value="A">One</option>
<option value="2" data-value="B">Two</option>
<option value="3" data-value="C">Three</option>
<option value="4" data-value="D">Four</option>
</select>
JS
$('select.example').change(function() {
var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');
console.log(other_val);
});
If you're goal is to write this information to the database, then why do you need to have a primary value and 'related' values in the value attribute? Why not just send the primary value to the database and let the relational nature of the database take care of the rest.
If you need to have multiple values in your OPTIONs, try a delimiter that isn't very common:
<OPTION VALUE="1|2010">One</OPTION>
or add an object literal (JSON format):
<OPTION VALUE="{'primary':'1','secondary':'2010'}">One</OPTION>
It really depends on what you're trying to do.
Put values for each option like
<SELECT NAME="val">
<OPTION value="1:2:3:4"> 1-4
<OPTION value="5:6:7:8"> 5-8
<OPTION value="9:10:11:12"> 9-12
</SELECT>
At server side in case of PHP, use functions like explode
[array] = explode([delimeter],[posted value]);
$values = explode(':',$_POST['val']
The above code returns an array that has only the numbers and the ':' get removed
Simplest way to do this:
<select name="demo_select">
<option value='{"key1":"111","key2":"222"}'>option1</option>
<option value='{"key1":"333","key2":"444"}'>option2</option>
</select>
on controller decode the request value as given below:
$values = json_decode($request->post('demo_select'));
$val1 = $values->key1;
$val2 = $values->key2;
echo "Value 1: ".$val1;
echo "Value 2: ".$val2;
output for the first option:
Value 1: 111
Value 2: 222
output for the second option:
Value 1: 333
Value 2: 444
Use a delimiter to separate the values.
<select name="myValues">
<option value="one|two">
</select>
<?php>
$value = filter_input(INPUT_POST, 'myValues');
$exploded_value = explode('|', $value);
$value_one = $exploded_value[0];
$value_two = $exploded_value[1];
?>
Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010". But you would have to parse the value on the server.
Instead of storing the options on the client-side, another way to do this is to store the options as sub-array elements of an associative/indexed array on the server-side. The values of the select tag would then just contain the keys used to dereference the sub-array.
Here is some example code. This is written in PHP since the OP mentioned PHP, but it can be adapted to whatever server-side language you are using:
<FORM action="" method="POST">
<SELECT NAME="Testing">
<OPTION VALUE="1"> One </OPTION>
<OPTION VALUE="2"> Two </OPTION>
<OPTION VALUE="3"> Three </OPTION>
</SELECT>
</FORM>
PHP:
<?php
$options = array(
1 => array('value1' => '1', 'value2' => '2010'),
2 => array('value1' => '2', 'value2' => '2122'),
3 => array('value1' => '3', 'value2' => '0'),
);
echo 'Selected option value 1: ' . $options[$_POST['Testing']]['value1'] . '<br>';
echo 'Selected option value 2: ' . $options[$_POST['Testing']]['value2'] . '<br>';
This may or may not be useful to others, but for my particular use case I just wanted additional parameters to be passed back from the form when the option was selected - these parameters had the same values for all options, so... my solution was to include hidden inputs in the form with the select, like:
<FORM action="" method="POST">
<INPUT TYPE="hidden" NAME="OTHERP1" VALUE="P1VALUE">
<INPUT TYPE="hidden" NAME="OTHERP2" VALUE="P2VALUE">
<SELECT NAME="Testing">
<OPTION VALUE="1"> One </OPTION>
<OPTION VALUE="2"> Two </OPTION>
<OPTION VALUE="3"> Three </OPTION>
</SELECT>
</FORM>
Maybe obvious... more obvious after you see it.
<select name="student" id="student">
<option value="">Select Student</option>
<option value="Student Name|Roll No">Student Name</option>
</select>
<input type="submit" name="submit" id="submit" value="submit"></form>
i use data-attribute to get the value with simple javascript and blade template.
<select class="form-control" id="channelTitle" name="channelTitle" onchange="idChannels()">
#foreach($post['channels'] as $channels)
<option value="{{ $channels->channel_title }}" data-id="{{ $channels->channel_id }}">{{ $channels->channel_title }}</option>
#endforeach
</select>
the data-id result here
<div class="form-group">
<strong>Channel Id:</strong>
<input type="text" name="channelId" id="channelId" class="form-control" placeholder="Channel Id">
</div>
javascript
<script>
function idChannels(){
var elem=document.getElementById("channelTitle");
var id = elem.options[elem.selectedIndex].getAttribute('data-id');
document.getElementById("channelId").value = id;
} </script>
you can use multiple attribute
<SELECT NAME="Testing" multiple>
<OPTION VALUE="1"> One
<OPTION VALUE="2"> Two
<OPTION VALUE="3"> Three