<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>
Related
I was able to populate a drop down list using a MYSQL server and I now want to take that value, ideally in PHP, and capture it into a variable. The end goal is to use that variable and create an SQL query to run on the server. Thanks!
<select id="lstPropName" name="lstPropName">
<option value=" ">Select Team Name</option>
<?php
$sql = "SELECT DISTINCT TeamName from $TName";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$lstPropName = $row['TeamName'];
?>
<option value="<?php echo $lstPropName;?>"><?php echo $lstPropName;?></option>
<?php
}
?>
</select>
$lstPropName = $_POST["lstPropName"];
Here is the complete code, it is inside a form tag:
https://github.com/SahasR/OpenSourceDebateTab/blob/10/01/2020Alpha/PersonalJob_Results.php
I have looked at this site for three days. I admit I am new to using javascript. But I have used the many different solutions offered and none have worked. Please help.
I am trying to do something that should be simple: save a user choice of country from a dropdown box on an html5 page to a hidden post variable (using javascript onchange.) That is used in a post array on the same form for a php operation that sends the input to a mysql database. This is my code:
The hidden post variable doesn't update. From there I can't test the code logic. But my onchange code came from this site and is suppose to work.
References:
<script type="text/javascript" src="../../js/jquery-2.1.4.min_prod.js"> </script>
<script type="text/javascript" src="../../js/respond.min.js"> </script>
<script type="text/javascript" src="../../js/bootstrap.min.js"> </script>
form information:
<form name="form1" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" />
</form>
form element
$query="SELECT * from country ";
$query=$query."ORDER BY country asc";
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select id="country" onchange="send_name(this)">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
?>
<input type="hidden" id="c_php_value" name="c_php_value" value="">
Javascript
function send_name(selectObjectI) {
var value = selectObjectI.value;
$.ajax({
type: "POST",
url: "http://localhost/php/protected/form_addnews.php",
data:{c_php_value: value}
});
Post Submit Code
$country_id1 = trim($_POST['c_php_value']);
Thanks to a coder on utube, speaking german I might add, I discovered I don't need javascript, ajax or anything complicated to accomplish what I am trying to do.
I simply needed to do the following:
(1) Add a name="" to the dynamically created SELECT flag(name="country_id2").
(2) user chooses input with drop down box created.
(3) gather the $_POST after the form submit is set.
($country_id = $_POST['country_id2'])
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select name="country_id2" id="country_id2">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
I'm trying to make a grade distributions website, and I'm creating 4 dropdowns correlating subject (cs, math, etc.), class (data structures, AI, etc.), professor, and quarter the class was taken. After the quarter dropdown is selected, I want to display a bar graph with the data.
The problem I'm running into is that I can't populate the second dropdown with data Basically, I can successfully pull data from the database for the first dropdown, and if the user selects something then the second dropdown (that was originally hidden using jquery) becomes visible, but it isn't properly pulling data from the database and adding it as options to the second dropdown. An example would be that I can select Computer Science from the first dropdown, then the second dropdown is visible, but it doesn't contain 'intro to programming', 'data structures', etc. in it; instead, it's just blank.
FYI, I'm using these selectpickers: http://silviomoreto.github.io/bootstrap-select/
PHP (error is most likely somewhere in the getClasses function, quite possibly the $_POST section of the code):
<?php
function getSubjects()
{
/* Get mysql connect information from external file and connect*/
require_once 'database.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
/* Get the column containing the subjects from the table */
$query = 'SELECT DISTINCT Subject FROM gradelist ORDER BY Subject';
$result = $connection->query($query);
if(!$result) die ($connection_error);
/* Keep track of the number of rows in the column; necessary for iterating */
$rows = $result->num_rows;
/* selectBar keeps track of the html code for the select Bar*/
$selectBar = '';
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Subject'];
$selectBar .= '<option>' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
}
function getClasses()
{
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
if(isset($_POST['subject']))
{
$query = "SELECT DISTINCT Class FROM gradelist WHERE Subject = $subject";
$result = $connection->query($query);
if(!$result) die ($connection_error);
}
else
{
die($connection_error);
}
$rows = $result->num_rows;
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Class'];
$selectBar .= '<option value = "' . $value . '">' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
} ?>
HTML Portion of the code (again, the error might be with the $_POST part of the code) :
<form class="form-horizontal" method = "post" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "subject" id="subject" class="selectpicker show-tick form-control" data-live-search="true" title ="Subject">
<?php echo getSubjects(); ?>
</select>
</div>
</div>
</form>
<form class="form-horizontal" method = "get" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "class" id="class" class="selectpicker show-tick form-control" data-live-search="true" title ="Class">
<?php if(isset($_POST['subject'])) echo getClasses(); ?>
</select>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#class').selectpicker('hide');
$('#professor').selectpicker('hide');
$('#quarter').selectpicker('hide');
});
$('#subject').on('change', function(){
$('#class').selectpicker('refresh');
$('#class').selectpicker('show');
});
$('#class').on('change', function(){
$('#professor').selectpicker('show');
});
$('#professor').on('change', function(){
$('#quarter').selectpicker('show');
});
$('#quarter').on('change', function(){
showTable();
temp = $('#class').selectpicker('val') + " with " + $('#professor').selectpicker('val') + " during " + $('#quarter').selectpicker('val');
$('#displayName').text(temp);
});
Your PHP is executed with $_POST["subject"] not set, and you never POST the subject the user chose to the page; if you don't make an additional POST request, there's no way for the classes to populate.
One way to do it (without changing any of your files) is like so:
$('#subject').on('change', function(){
$.post({
data: { subject: $(this).val() },
success: function (data) {
var classes = $(data).find("#class");
$("#class").replaceWith(classes);
}
});
});
So when a change event is triggered on the subject selection, we'll POST the selected subject to the current page. The response should be the entire document generated with the class selection filled (since $_POST["subject"] is set).
We then replace the current page's #class select element with the version in the generated data (wrapped in $() to create DOM elements from the stringified HTML, so we can use find()).
Another way might be to have files, getSubjects.php, getClasses.php, and so on, and POST individually to them (you make the first request onload, and subsequent requests onchange). This way, you can just append the generated option elements to the select elements on the page.
ALSO: Please please please sanitize $_POST["subject"] before using it in a database query. A user could easily add a fake option to the select locally with a malicious string for value, and you'd unknowingly query the DB with that. You can use prepared statements for this (mysqli has the prepare() function to prepare a statement before querying). More on that and combating SQL injection here.
Hi I am trying to create a set of drop down boxes that will use an array of data from the values that you pick and then runs through a loop to post them to the screen at the moment the data that i want to use will just be local but i want to edit this later so that it will loop through the data from my database and post that to the screen. i have looked at other questions on this subject and just wondering how i would change it for my code i have looked at this link questions on stack overflow that I have looked at i have just got a couple questions that im wondering if anybody has seen this before or if they have seen any examples i have also looked at for loops and i understand the concept
my questions to you are:
1) how would I post the values from my drop down boxes into a php array
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
3)Would I need to use a second language like javascript or can it be done just in php
My drop down box code is
<div id="Content">
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="%">any...</option>
</select>
<br /><br />
Choose a principle:<br />
<select id="principle">
<option value="%">any...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<!-- end of the Options -->
below is the select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM subject";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM section WHERE subject_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description'] . '</option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT * FROM principle WHERE section_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description'] . '</option>';
}
return $principle;
}
}
$opt = new SelectList();
?>
1) how would I post the values from my drop down boxes into a php array
In the form tag add method="POST". Reference in PHP with $_POST array. Make sure to validate and escape the data before writing to your DB.
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
If you don't have millions of categories, you are better off sending them all as a JSON array and using Javascript. Something like:
<script>
var categories = <?php echo json_encode($opt->ShowCategory()); ?>;
</script>
json_encode may require some options to be set, depening on your character set. More info here: http://php.net/manual/en/function.json-encode.php
Making a new request each time someone changes a dropdown box will drive them crazy, I know I hate that. If you have used jQuery before, this is very easy. This isn't that difficult without it.
3)Would I need to use a second language like javascript or can it be done just in php
For the sake of your users, use Javascript.
code for showCategory()
...
$categories = new array();
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$categories[$row['subject_id']] = $row['description'];
}
$validCategories = $this->getValidCategories() // get the valid categories
foreach($categories as $index=>$cat){
// only choose the categories that are valid
if(array_search($cat,$validCategories) !== FALSE)
$category.= '<option value="'.$index.'">'.$cat.'</option>';
}
return $category;
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;
});
});