I've been building a script for dynamic dropdowns using PHP and JQuery and I'm having an issue with some of the data being sent from the form to be queried. Basically the user will choose an option from the first box and from there ever other box is dependent on the previous. The options are pulled from a MySQL database and as these same options are being picked they are sent back to the script to create the next query and so on. I'm having issues with some of the data and I think it's because there are spaces in the options being sent through GET. I've looked over my script many times the past few days and I just can't find a solution.
Here is a live version of my script to test. - That's the url for a live version of the script to check out.
Here is the front-end. A pretty basic form and some javascript to send the information to the back-end script:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$("#series").change(function() {
$("#range").load("findbackend.php?series=" + $("#series").val());
});
$("#range").change(function() {
$("#digsize").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val());
});
$("#digsize").change(function() {
$("#dignum").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val() + "&digsize=" + $("#digsize").val());
});
});
</script>
</head>
<body>
<select id="series">
<option selected value="base">Please Select</option>
<option value="FM800">FM800</option>
<option value="F100">F100</option>
</select>
<br>
<select id="range">
<option>Please choose from above</option>
</select>
<br>
<select id="digsize">
<option>Please choose from above</option>
</select>
<br>
<select id="dignum">
<option>Please choose from above</option>
</select>
</body>
</html>
And here is the back-end I've come up up with:
<?php
//\\ MODULAR DEPENDANT DROPDOWNS \\//
//creates DB connection
$dbHost = 'host';
$dbUser = 'user';
$dbPass = 'pass';
$dbDatabase = 'database';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
$series = mysql_real_escape_string($_GET['series']);
isset($_GET['range'])?$range = mysql_real_escape_string($_GET['range']):"";
isset($_GET['digsize'])?$digsize = mysql_real_escape_string($_GET['digsize']):"";
isset($_GET['dignum'])?$dignum = mysql_real_escape_string($_GET['dignum']):"";
//forms the query depending on what data is recieved through GET
if (isset($_GET['dignum'])) {
$query = "SELECT DISTINCT * FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' AND dig_num='$dignum' ORDER BY sio";
} elseif (isset($_GET['digsize'])) {
$query = "SELECT DISTINCT dig_num FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' ORDER BY sio";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT dig_size FROM meters WHERE series='$series' AND sio='$range' ORDER BY sio";
} else {
$query = "SELECT DISTINCT sio FROM meters WHERE series='$series' ORDER BY sio";
}
//creates a result array from query results
$result = mysql_query($query);
//outputs dropdown options dependent on what GET variables are set
if (isset($_GET['digsize'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'dig_num'} . "'>" . $row{'dig_num'} . "</option>";
}
} elseif (isset($_GET['range'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'dig_size'} . "'>" . $row{'dig_size'} . "</option>";
}
} else {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sio'} . "'>" . $row{'sio'} . "</option>";
}
}
?>
Again, new.foxmeter.com/find.php is a live version of my script to check out.
This is a monospaced snippet of my table that I'm pulling data from: i.imgur.com/IOT9RUF.png
Thanks in advance for any help!
Your instincts were right, the problem is with non-escaped characters (url encoding). For debugging AJAX calls you should use your browser's console (I highly recommend FireBug, but to each his own).
Before you send the parameters via AJAX, you have to encode them using encodeURI(). For example:
$("#series").change(function() {
var val = document.getElementById('series').value;
// $("#series").val() == document.getElementById('series').value
// but the latter is faster!
$("#range").load(encodeURI("findbackend.php?series=" + val));
});
You would also have to adjust your other .change function calls accordingly. Since the data your PHP script will receive has been encoded, you need to decode it using urldecode(). Example:
$series = mysql_real_escape_string(urldecode($_GET['series']));
This should work just fine.
On a side note, you are using a deprecated MySQL API, you should use MySQLi or PDO. Also, your jQuery calls could do with some caching (you create the $("#series") object three separate times).
the easy way to use ajax so you need two php pages and one js at least
the first php will have the first dropdown and then send it`s value to the second php by ajax
it's simply example
first php code like this
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="dropdown.js"></script>
</head>
<body>
<select name="first" id="first">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<div id="second"></div>
</body>
</html>
dropdown2.php code is
<?php
if(isset($_GET['first'])){
$first=$_GET['first'];
echo"
<select name='second' id='secondselect'>
<option value='4'>$first a</option>
<option value='5'>$first b</option>
<option value='6'>$first c</option>
</select>
";
}
?>
and dropdown.js
$(document).ready(function(){
$("#first").change(function(){
str=$("#first").val();
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","dropdown2.php?first="+str,false);
xmlhttp.send();
document.getElementById("second").innerHTML=xmlhttp.responseText;
});
});
Related
<body>
<H1>4a</H1>
<form action="hw4b.php" method="post">
<?php
$con = mysqli_connect("localhost","[credential]","","[credential]")
or die("Failed to connect to database " . mysqli_error());
?>
<select name="id" value="id">
<script>
for (x=1;x<=101;x++)
{
document.write("<option value="+x+">"+
<?php echo mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE CUSTOMERID == "+x+";")?>
+"</option>");
}
</script>
</select>
<input type="submit" value="SEND IT">
</form>
</body>
So this should put the corresponding LASTNAME into the select, but it just fills every row with "NaN". I'm sure this is some stupid minor error, but I've been staring at it too long.
you should query the results of mysqli_query
do something like this:
<select name="id" value="id">
<?php
$query = mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE WHERE CUSTOMERID >=1 and CUSTOMERID <= 101 ;");
while ($row = mysqli_fetch_array($query))
echo "<option id='".$row['LASTNAME']."'>".$row['LASTNAME']."</option>";
?>
</select>
notes:
no need for javascript usage
please escape the query parameter
id of the option is the value that will be sent to the server, makes more since to send LASTNAME
avoid using a query at a loop
Note that your for cycle is in javascript (between <script> tags), yet you try to fill in some data in php.
Everything in PHP happens on server side, i.e. is interpreted, packed into a http response and returned to the client, where it is unpacked and javascript is executed.
You need to either put both into javascript, or both into php.
<select>
<?php
for ($i = 0; $i < 100; i++){
///make some select here
echo "<option value="$i"> ...output the select </option>"
}
?>
</select>
This way, all options are generated on server side and transferred to client as text
<select>
<option value="0">...</option>
<option value="1">...</option>
...
Other option is to export the database data into javascript, and then access it in javascript.
<script>
//or perhaps better
var myOtherData = <?=json_encode($somePHPData)?>;
</script>
//now you can use for loop with document.write and one of the variables you exported...
You need to be very careful and sure which execution happens on server, and which on client side.
There are several issues I think. You are using a comparison operator in the SELECT statement, it should just be =, not ==. Also, mysqli_query returns a mysqli_result, not a value like "Johnson" for LASTNAME. And, maybe most importantly, it doesn't make sense to do this with javascript since you're writing the values to the document before sending it to the browser anyway.
The code should look something like this (not tested)
<select name="id" value="id">
<?php
$query = 'SELECT LASTNAME, CUSTOMERID FROM CUSTOMERS WHERE CUSTOMERID >= 1 AND CUSTOMERID <= 101 ORDER BY CUSTOMERID ASC';
$result = mysqli_query($con, $query);
if (!$result) {
echo 'some error handling';
} else {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['CUSTOMERID'] . '">' . $row['LASTNAME'] . '</option>';
}
}
?>
</select>
i am trying to populate second dropdown based on the selected option of 1st dropdown but i am unable to do so i dont know what i am doing wrong but something is wrong all my endeavors to achieve my desired results are dashed to the ground cuz its not working kindly help me
so far i have done this....
<select name="ddl_company" size="1" class="form-control" id="ddl_company" onchange="getId(this.value);">
<option value="">Select Company</option>
<?php
//Getting Company name from mysql and displaying it in the 1st dropdown having id ddl_company
$query = mysql_query("select * from company where company_status='Active'order by company_name asc");
while ($r = mysql_fetch_array($query)) {
if ($r['company_id'] == $ddl_company) {
echo "<option selected value=$r[company_id]>$r[company_name]</option>" . "<BR>";
} else {
echo "<option value=$r[company_id]>$r[company_name]</option>";
}
// second drop down list which is going to fetch data from mysql db based on the selected option of 1st dropdown
?>
<select name="ddl_dept" size="1" class="form-control" id="ddl_dept">
<option value=""></option>
</select>
//ajax implementation of 2nd dropdown
<script type="text/javascript">
function getId(val)
{
$.ajax({
type:"POST",
url:"getdata.php",
data:"company_id="+val,
success:function(data)
{
$('#ddl_dept').html(data);
}
});
}
</script>
finally get_data.php file
<?php
include("../newconfig.php");
if (!empty($_POST['company_id'])) {
$company_id = $_POST['company_id'];
$query = "select * from department where department_status='Active'LIMIT 1 AND company_id='$company_id'LIMIT 1";
$sqlquery = mysql_query($query);
while ($r = mysql_fetch_array($sqlquery)) {
# code...
if ($r['company_id'] == $company_id) {
echo "<option selected value=$r[department_id]>$r[department_name]</option>" . "<BR>";
} else {
echo "<option value=$r[department_id]>$r[department_name]</option>";
}
}
}
}
?>
I have done all this yet its not working kindly help me i shall be very thankful. btw thats my output
click this to show the result
Try something like this : jquery
$("select#ddl_dept").on('change',function(){
var selected = $('#ddl_company option:selected').text();
getId(selected );
});
I need help with generating dynamic dropdowns using PHP, Javascript and mySQL. I am not good with AJAX and Javascript and hence I'm asking for help here.
I have a table named Hotel, which contains a list of hotel names and categories. They are categorised by locations such as North, South, East and West. I am trying to allow the user to pick the categories they want, then the second dropdown will generate a list of available hotels under that particular category. As mentioned, I am not good with AJAX or JS.
The question has been solved! I have edited my answer to work with the database, assuming basic user root and no password. the table hotel has 3 columns, id, category and name.
booking.php
<div class="form-group">
<label class="control-label col-sm-3" for="PreferredHotel">Preferred Hotel:</label>
<div class="col-sm-3">
<select class="form-control" name="hotelCategory" onchange="fetchHotelNameByArea(this.value)">
<option value="0">Please select area above first</option>
<?php
mysqli_select_db($dbConn, $database_dbConn);
$query_hotelselect = "SELECT * FROM hotel GROUP BY Category";
$hotelselect = mysqli_query($dbConn, $query_hotelselect) or die(mysqli_error($dbConn));
$row_hotelselect = mysqli_fetch_assoc($hotelselect);
while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
echo "<option value='" . $row_hotelselect['Category'] . "'> " . $row_hotelselect['Category'] . " </option>";
}
?>
</select>
<?php
echo $row_hotelselect;
?>
</div>
<div class="col-sm-3" id="fetchHotelNameByAreaResult">
<select class="form-control">
<option value="0">Please select area above first</option>
</select>
</div>
<script>
function fetchHotelNameByArea(HotelArea) {
//above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
var xhttp = new XMLHttpRequest();
var url = "getter.php";//<- just a sample url
var data = new FormData();
//below will "assign HotelArea to $_POST['SearchValue']"
data.append('SearchValue', HotelArea);
xhttp.open('POST', url, true);
xhttp.send(data);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
}
}
}
</script>
</div>
getter.php
<?php
if ($_POST['SearchValue']) {
$searchname = $_POST['SearchValue'];
require_once('Connections/dbConn.php');
mysqli_select_db($dbConn, $database_dbConn);
$query_preferredhotel = "SELECT * FROM hotel WHERE Category = '$searchname'";
$preferredhotel = mysqli_query($dbConn, $query_preferredhotel) or die("Could not select examples");
$row_preferredhotel = mysqli_fetch_assoc($preferredhotel);
echo'<select class="form-control" name="preferredHotel">';
while ($row_preferredhotel = mysqli_fetch_assoc($preferredhotel)) {
echo "<option value='" . $row_preferredhotel['Name'] . "'> " . $row_preferredhotel['Name'] . " </option>";
}
}echo '</select>';
?>
Kinda got stuck here after making the dropdown list appear. I found an article on https://css-tricks.com/dynamic-dropdowns/ but they do not have the example for the database and I was hoping someone could help me with this as I understand I would most likely need AJAX to request for data from the database/server and populate the second dropdown. Im not asking for spoonfeeding, but I really have very little clues about AJAX. Any guidance would be helpful!
EDITED
The issue with only part of the keywords being passed has been solved, thanks to Mark Ng spotting my markup error! I am really thankful for all your help in answering my questions, thank you!
sample concept.
There are 2 select(dropdown), the first will populate the second based on its category.
1st select
<select onchange="fetchHotelNameByArea(this.value)">
<option value="North">North</option>
<option value="South">South</option>
<option value="East">East</option>
<option value="West">West</option>
</select>
2nd select(to be populated by javascript later)
<div id="fetchHotelNameByAreaResult">
<!--For temporary only, this select was purposely placed inside this div id, it will get re-written by javascript when result are generated-->
<select>
<option value="0">Please select area above first</option>
</select>
</div>
JS(Native)
<script>
function fetchHotelNameByArea(HotelArea) {
//above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
var xhttp = new XMLHttpRequest();
var url = "./php/find_hotel_name_by_area.php";//<- just a sample url
var data = new FormData();
//below will "assign HotelArea to $_POST['SearchValue']"
data.append('SearchValue',HotelArea);
xhttp.open('POST',url,true);
xhttp.send(data);
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
}
}
}
</script>
php query (The select will be returned to div id="fetchHotelNameByAreaResult" by javascript
<?php
if($_POST['SearchValue']) {
$searchname = $_POST['SearchValue']
//.... your query
//"SELECT * FROM hotel WHERE Category = '$searchname'";
echo '<select class="blablabla">';
while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
echo "<option value=" . $row_hotelselect['id'] . "> " . $row_hotelselect['Name'] . " </option>";
}
}
echo '</select>';
?>
What is going on?
1. Upon 1st select, the onchange gets fired, calling function fetchHotel...
2. JS send data to server, where a php file will process the request, onreadystate... will detect if response is ready, and innerHTML will re-write whatever is in div id="fetchHotelNameByAreaResult" with the resposeText generated by the php script.
There are other ways to do it via jQuery, etc. But once you get the basic concept, you are ready to move on.
EDIT to address this issue.
Hey there again, the codes above works fine. But however, I realised
that the dropdown list only passes one part of the value inside the
variable (eg. ritz carlton, only passes ritz to the next form). Anyone
aware of any solutions?
There is a html markup error.
echo "<option value=" . $var . ">" . $var . "</option>";
//The above will return <option value=ritz carlton>ritz carlton</option> in html.
//the problem lies with value=ritz carlton as there is a space in between.
//html will think that it is value="ritz" while carlton is not a valid attribute, it will simply ignore it and only set the value as ritz, so only the value ritz was posted.
//In order to get the full string parse, you have to quote them like below.
echo "<option value='". $var ."'>" . $var . "</option>";
// echo "<option value=" . "'" . $var . "'" . "</option>";
// echo "<option value=/" " . $var . " /"</option>";
//a lot more ways to achieve same result.
//These will return <option value="ritz carlton">ritz carlton</option> in html. This will set the value as ritz carlton and the value "ritz carlton" will be posted.
?>
I read your question and understood your problem.
Basic steps :
First create a section behind your first drop down in which hotel name will be fetched according to the category selected in first drop down.
Example :
<div class = "hotelDropDown">
// hotel drop down
</div>
After, create an ajax request that will fetch the category name from first drop down and will send the request to the php file to fetch the hotel name correspinding to the selected category name and make the drop down.
Example :
$.ajax({
url : "hotelfetch.php",// function to create hotel dropdown
data : {categoryName : $('.hotelCategory').val()}
success :
function(data){
//generate dropdown of hotel name
});
});
Make a view file of hotelfetch.php in which you create a dropdown of hotel name according to fetched category name and replace it in the html of the section created below category drop down which I created for you.
I'm working on a form. There are select elements and their options are from a database.
When i choose the first (for example a school class) the second have to show only those names who are in the class selected at first, from database too.
I'm rookie at Javascript and JQuery so I'm okay with page refreshing PHP solutions but I can't figure it out on my own. Can you please give me some instructions or advices how to start to work on this?
You can achieve this with ajax using preferably jquery and json.
javascript/ajax:
function fillSecondSelect()
{
$.get("ajaxFill.php?id=" + $("#class").val(),"",function(data) {
var selectData = "<option value=''> - Choose Student - </option>";
data = JSON.parse(data);
for(i=0;i<data.length;i++)
{
selectData += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#students").html(selectData);
});
}
html:
<select id="class" name="class" onchange="fillSecondSelect()">
<option value=""> - Choose Class - </option>
<option value='1'>Class A</option>
<option value='2'>Class B</option>
</select>
<select id="students" name="students"></select>
ajaxFill.php (which should get the student data according the class id sent from mysql and serve it as JSON):
$result = mysqli_query($link,"SELECT * FROM students WHERE class_id = '" . $_GET['id'] . "'") or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result))
{
$students[] = array("id" => $row['student_id'], "name" => $row['student_name']);
}
echo json_encode($students);
You use Jquery and Ajax to fetch the Students in a class based on the Class selected and load the student list into a Select element without refreshing the page.
HTML
<select id="selectedclass" onBlur="loadstudent();">
<option>class 1</option>
<option>class 2</option>
<option>class 1</option>
</select>
<select id="students" ></select>
Javascript
function loadstudent(){
var selectedclass = $('selectedclass').val();//user id
$.ajax({
type:'POST',
url: your php script,
data: 'selectedclass='+selectedclass,
dataType: 'json',
success: function(data)
{
var classlist='', html;
for(var i = 0; i < data.length; i++) {
classlist = data[i];
html+=classlist.students
}
//get number of outbox
$('#students').html(html);
},
error: function(jqXHR, exception) {
alert('Error');
}
});
}
PHP
<?php
include "config.php";//database connection file
//database using PDO
$db = pdoDB::getConnection();
//data from html
$student_class=$_POST['selectedclass'];
$query = "SELECT student_lastName,student_firstName
FROM student_table WHERE student_class='student_class'";
$result = $dbase->query($query) or die("failed!");
while ($row = $result->fetch(PDO::FETCH_BOTH)){
//credits info
$studentlist="<option>".$row['student_lastName']." ".$row['student_firstName']."</option>";
$results[] = array("students"=>$studentlist);
}
header('Content-type:application/json');
exit (json_encode($results));
?>
The data sent from the PHP script should be encoded with JSON
Modern websites use ajax to do this.
After the first item is selected an ajax request is sent which delivers the data for the second select.
There are many ways to build the second select. The ajax response could contain a json array with all the data and then you build the select field with js.
Or the response delivers complete html and all you have to do is to insert it.
I think this is exactly that you mean: http://codepen.io/man/pen/oBFlE
Put the js code in your file. You can have as many levels as you want. Explaining:
<select name="level1"><!--this is the "main" select-->
<option value="level2A">Level2A</option>
<option value="level2A">Level2B</option>
</select>
<select name="level2A"><!--this shows when the user selects the option with name ""level2A"-->
<option value="level3"></option>
</select>
<select name="level2B">
<!--options...-->
</select>
<select name="level3"></select>
I've created a dynamic dropdown using JS/PHP/MySQL but it seems I'm having some problems with UTF8 decoding in my PHP. The script is going to be used to make a small application that helps my customers find a product that meets their criteria. We sell panel meters that can accept different ranges of input and many are denoted with a +/- or a value (example: a meter can expect to process a voltage +/- 10V around a specified voltage.) Everything is starting to work great in my script except when some characters are parsed through (+, / , ±, ½, etc.) My database originally used ± to denote plus or minus but I then switched to +/- (three characters) in hopes that it would fix the special character problem but it didn't...
Using console.log I've figured out that my JS is encoding the special characters correctly but once it gets to my PHP it doesn't decode properly.
Everything along the way is set to UTF8
So now I still need to figure out why some things are not parsing right.
You can view a live version of the script at http://new.foxmeter.com/find.php.
This is the important part of my frontend
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$("#type").change(function() {
var tval = document.getElementById('type').value;
$("#range").load(encodeURI("findbackend.php?type=" + tval));
});
$("#range").change(function() {
rval = document.getElementById('range').value;
$("#power").load(encodeURI("findbackend.php?range=" + rval));
console.log(encodeURIComponent(document.getElementById('range').value));
});
$("#power").change(function() {
//var rval = document.getElementById('range').value;
psval = document.getElementById('power').value;
$("#setpoint").load(encodeURI("findbackend.php?range=" + rval + "&power=" + psval));
});
$("#setpoint").change(function() {
//var rval = document.getElementById('range').value;
//var psval = document.getElementById('power').value;
stval = document.getElementById('setpoint').value;
$("#output").load(encodeURI("findbackend.php?range=" + rval + "&power=" + psval + "&setpoint=" + stval));
});
});
</script>
</head>
<body>
<!-- Google Analytics Script -->
<?php include_once("scripts/analyticstracking.php") ?>
<div class="wrapper"> <!-- Sticky Footer Wrapper -->
<div id="panorama"></div>
<div id="header">
<?php include("include/header/banner.php") ?>
<?php include("include/header/nav.php") ?>
<?php include("include/header/quicksearch.php") ?>
</div>
<div id="content">
<div id="findoptions">
<select id="type" class="finddrops">
<option selected value="base">Please Select</option>
<option value="DC Voltage">DC Voltage</option>
<option value="DC Current">DC Current</option>
<option value="AC Voltage">AC Voltage</option>
<option value="AC Current">AC Current</option>
<option value="Strainguage">Strainguage</option>
</select>
<br>
<select id="range" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="power" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="setpoint" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="output" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="blarg" class="finddrops">
<option>Please choose from above</option>
</select>
</div>
<div id="findresults" class="finddrops">
</div>
</div>
</div>
And this is my PHP running on the backend:
<?php
//\\ MODULAR DEPENDANT DROPDOWNS \\//
//creates DB connection
$dbHost = 'host';
$dbUser = 'user';
$dbPass = 'password';
$dbDatabase = 'database';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
//any order
$type = mysql_real_escape_string(urldecode($_GET['type']));
isset($_GET['range'])?$range = mysql_real_escape_string(urldecode($_GET['range'])):"";
isset($_GET['power'])?$power = mysql_real_escape_string(urldecode($_GET['power'])):"";
isset($_GET['setpoint'])?$setpoint = mysql_real_escape_string(urldecode($_GET['setpoint'])):"";
//forms the query depending on what data is recieved through GET
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' AND stp='$setpoint' ORDER BY model";
} elseif (isset($_GET['power'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' ORDER BY model";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT pso FROM meters WHERE sio='$range' ORDER BY model";
} else {
$query = "SELECT DISTINCT sio FROM meters WHERE sit LIKE '%$type%' ORDER BY model";
}
//creates a result array from query results
$result = mysql_query($query);
//outputs dropdown options dependent on what GET variables are set
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['power'])) {
echo "<option>Choose Setpoint Options</option>";
while ($row = mysql_fetch_array($result)) {
$row{'stp'} = ucfirst($row{'stp'}); //capitalizes the first letter; necessary?
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['range'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'pso'} . "'>" . $row{'pso'} . "</option>";
}
} else {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sio'} . "'>" . $row{'sio'} . "</option>";
}
}
//Thanks to Chris Coyier for the wonderful examples on CSS-Tricks
//A Web Application by Zach Klemp
?>
Again, you can view the script here.
Choose DC Voltage in the first dropdown and then a +/- option in the second the see where the problem begins. When you choose Straingauge in the first dropdown and then click '30 mV with 10 V DC excitation' it parses through fine. (And as an aside another problem I have is that choosing the first result without clicking another first doesn't trigger the .change)
Thanks for any and all help getting this to work! I've been trying to figure this out for a bit now and haven't come up with a solution.
Try this in your PHP file :
Replace any echo XXXX; with utf8_decode(XXXX)
It should make it works
$string = ';http%3A%2F%2Fwww.google.com%2F%3Fq%3Dtesting%2Burldecode';
echo urldecode($string); // http://www.google.com/?q=testing+urldecode
For further reading, see the official PHP documentation on urldecode here.