I can't seem to get the value for a 'selected item' to pass to a JavaScript function with PHP that uses the value to query data from MySQL database -> populates a different drop down list.
Here is my 'HTML' code
<select name="numbers" id="numbers" onChange="populateOtherSelect()">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
<?php echo $option ?>
Here is my 'JavaScript' function code
function populateOtherSelect() {
<?php
// code that opens db connection
$numbers = $_POST['numbers'];
$query = "select*from Database.Table where Something = 'Something' and Numbers like '%".$numbers."%'";
$result = mysql_query($query);
$option = "";
while($row = mysql_fetch_array($result))
{
$OtherOptions = $row["OtherOptions"];
$option.="<option value=\"$OtherOptions\">".$OtherOptions."</option>\r\n";
}
// code that closes db connection
?>
}
Any information will be helpful.
Thanks very much
It seems your javascript code is part of the html / php document and that´s not going to work; the php is run only at initial page-load and at that moment there probably is no $_POST variable.
What you need to do, is make an ajax call to a php script at the moment your first select is changed and use the response from that ajax call to populate your second select.
So basically your javascript function would have to look like:
function populateOtherSelect() {
/*
* 1. get the value of the numbers select
* 2. make an ajax call to a php script / the server that gets some information from a database
* 3. use the response from the ajax call to populate your second select
*/
}
I think you need to add a space in your select statement:
$query = "select * from Database.Table where Something = 'Something' and Numbers like '%".$Numbers."%'";
First of all, the $Numbers variable doesn't exist, it's $numbers.
Related
I have a MySQL database containing 12 columns. I created a dropdown from it using distinct values of the column named 'activity' and the column named 'logdate' which is a datetime.
Like this..
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($db_found->query("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity") as $act) {
echo ("<option value='$act[activity]'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
This all works great. what I want to do is use the results of the selected option to do another query against the same database that pulls all of the records associated with the selected activity and logdate values. I know how to write the query but I don't know how to find and then use the selected values.
Can someone please show me how to get the selected value from the
Thanks in advance for your consideration.
I make some changes in your code, I didn't test it, but I think that's going to help you:
<?php
//Returns an associative array with the query result:
function select($yourSQLQuery){
//Array with result:
$result = array();
//Database conection
$db = new PDO($dsn,$username,$password);
$stmt = $db->query($yourSQLQuery);
//This going to save an array with your data:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
$db = null;
return $result;
}
//*********************************************************************************************
//Do here your query:
$result = select("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity");
//*********************************************************************************************
//Form handler:
if($_SERVER[REQUEST_METHOD] == "POST"){
//If the form was submited:
//Get selected activity
if ( isset($_POST['activities']) ) {
/*Instead of sending your activity you can send the number of the submitted record in $records, then extract activity and logdate and make your query:*/
$rowNumber = $_POST['activities'];
//Get your log date:
$act = $result[$rowNumber]; //if doesn't work try '$rowNumber'
$activity = $act['activity'];
$logdate = $act['logdate'];
//Pull records asocciated with submitted activity:
$sql = "SELECT * FROM putHereYourTable WHERE activity = '$activity' AND logdate='$logdate'";
$records = select($sql);
//Pulled activities are now in $records
//do something with the records that you want. e.g.:
print_r($records);
}
}
?>
<!-- Your HTML: -->
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($result as $key => $act) {
//Send the number of register instead of $act[activity]:
echo ("<option value='$key'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
You need to submit the form first.
<form action="define_activity" id="activityform" method="post">
You need to submit to a valid page in your action param. So if 'define_activity' is not a valid URL (ie: not handled by htaccess) then you need to either A) use the same script/file your using or B) create another page to handle the data.
I would do this:
<form action="process.php" id="activityform" method="post">
process.php
<?php
if ( isset($_POST['activities']) ) {
// do something with the submitted data
$selectedValue = $_POST['activities'];
}
Now you have the selected value. You have also any other value that is submitted in the form, $_POST['othervalue'].
For a clear view of what is sent, dump it.
die('<pre>' . print_r($_POST, true) . '</pre>');
or you could use var_dump: die( var_dump($_POST) );
Keith,
You have to remember that web applications work in a client server environment over the HTTP protocol.
After your page is done loading the first time, the php script is basically done executing. In order for more code to run, another request needs to be sent to the server. This happens when you either:
a) submit a form or click a link that sends a new http request to the page
b) make some javascript send a new HTTP request to the page.
Since you're just getting started, lets assume you just want that form to send the new request off to the page.
So at the top of your php script, just add this statement:
print_r($_REQUEST);
As you visit the page that is running the script both with and without clicking the submit post button, you will be able to see the various request parameters show up based on your form post. One of those params will be 'activity' .. just throw an if statement checking to see if that parameter is present, then run your query inside that if statement, using the value of 'activity'
if(isset($_REQUEST['activities'])) {
//do your query here..
}
i am using the following multiselect box to take input from users, this then gets posted to my php form which adds it to the database, the problem is, all I am getting added is the first selection, if the user selects more than one field I still only get the first field.
If the user selects lets say internet, drawing,maths I want that to be put into the database, at the moment all that is inserted is internet, or whatever is the first thing selected in the list.
My form looks like this >>
<form action="../files/addtodb.php" method="post" style="width:800px;">
<select name="whatisdeviceusedfor[]" size="1" multiple="multiple" id="whatisdeviceusedfor[]">
<option value="games">Games</option>
<option value="takingphotos">Taking Photos</option>
<option value="maths">Maths</option>
<option value="reading">Reading</option>
<option value="drawing">Drawing</option>
<option value="internet">Internet</option>
<option value="other">Other (enter more info below)</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
The php side looks like this >>
<?php
// Implode what is device used for
$usedfor = $_POST['whatisdeviceusedfor'];
$arr = array($usedfor);
$whatisdeviceusedfor = implode(" ",$arr);
// Insert posted data into database
mysql_query("INSERT INTO itsnb_year5questionaire (whatisdeviceusedfor) VALUES '$whatisdeviceusedfor'") or die(mysql_error());
?>
you are already getting array by select so you dont need to use $arr = array($usedfor);this again
just try
$usedfor = $_POST['whatisdeviceusedfor'];
$whatisdeviceusedfor = implode(" ",$usedfor);
or
$usedfor = $_POST['whatisdeviceusedfor'];
$strings ='';
foreach ($usedfor as $item){
$strings .=' '. $item;
}
echo $strings;
and
<select name="whatisdeviceusedfor[]" size="5" multiple="multiple" id="whatisdeviceusedfor[]">
^^
||change to option you want to select
i have changed size="5" so it will select now 5 at a time ...you have only 1 so it will let only 1 select at a time
result
warning
your code is vulnerable to SQL injection also use of mysql_* function are deprecated use either PDO or MySQLi
If you have selected mutliple items via a SELECT or via CHECKBOXES, the form will return an array-like data structure. You will always need to loop over that data and store each item individually into the database or concatenate the values to a string before inserting.
first change size = "5" to see good the list
then try to make like that (its second option if you like it)
if ($_POST) {
// post data
$games = $_POST["games"];
$takingphotos = $_POST["takingphotos"];
.
...
// secure data
$games = uc($games);
$boats = uc($takingphotos);
.
...
}
// insert data into database
$query = "INSERT INTO itsnb_year5questionaire (games, takingphotos,....)
VALUES('$games','$takingphotos',......)";
mysql_query($query) or die(mysql_error());
echo 'Thanks for your select!';
Because $usedfor is contain the array you can directly use it in foreach to save the each value in the value.Try this it may help you:
<?php
$usedfor = $_POST['whatisdeviceusedfor'];
foreach($usedfor as $arr){
mysql_query('INSERT INTO itsnb_year5questionaire(whatisdeviceusedfor) VALUES("'.$arr.'"') or die(mysql_error());
}
As title says I need help with onchange. I have select tag,and I need to do different mysql query when I choose something from select list. Example:
<select name="list">
<option>cars</option>
<option>busses</option>
<option>trucks</option>
</select>
and then when i select cars it do this
$query="select * from table where type='cars'";
and if I choose trucks it do
$query="select * from table where type='trucks'";
and so on...
then I need to display the result in div under the list
example
<select name="list">
<option>cars</option>
<option>busses</option>
<option>trucks</option>
</select>
<div> this is where I need to display results from query</div>
Please help!!!
If you want to change the result by ajax :
HTML :
<select id="list" name="list">
<option>cars</option>
<option>busses</option>
<option>trucks</option>
</select>
in JS File:
$(document).ready(function() {
$('#list').change(function() {
var selected=$(this).val();
$.get("change_query.php?selected="+selected, function(data){
$('.result').html(data);
});
});
});
and you should create change_query.php file and your query and code in it and return the result in it
$type = $_POST["selected"];
$query="select * from table where type='".$type."'";
print result here .... ;
Tell me if you need any help ,I just guided you in Jquery not all code
You should add your SELECT code to a form with method attribute set to post,
and also a submit button of course.
Then , php will get the value of those INPUTS and do whatever you want.
$term = $_POST['list'];
/*
In order to prevent unwanted queries or injection add an array with those terms and
check if the posted value is in this array:
*/
$terms = array("cars" , "trucks");
if(!array_key_exists($term , $terms))
die(); //bad bad bad boy.
$query = "select * from table where type='$term'";
you could use
onchange="this.form.submit();"
as well.
I am writing a reservation system. On the main page I would give a choice of category, viewed the equipment available for booking.
For example I have code like this:
<select>
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
I wish that each choice was associated with a separate query to the database, and that was the result of a query dynamically displayed on the screen.
It would be great if you could show me some sample code.
Regards
$query = mysql_query("SELECT * FROM choices");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
If you need separate query for each choice the code doesns't change much:
$query = mysql_query("(SELECT * FROM choices) UNION (SELECT * FROM choices1) [etc]");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
There are two parts to your question; 1 - Detecting which query to run and 2 - Displaying the results dynamically.
Part 1: Detecting which query to run:
Given hard-coded choices and no parameters for the query, using your above code, you can determine which query to run using the following:
For the HTML part, as part of a form, create the select as you did above (but with a name)
<select name="querySelect">
<option value="a">A</option>
<option value="b">B</option>
</select>
And in the PHP:
$querySelect = $_GET['querySelect'];
switch($querySelect)
{
case 'a':
$sql = "SELECT * FROM TableA";
break;
case 'b':
$sql = "SELECT * FROM TableB";
break;
}
$results = mysql_query($sql);
Part 2: Displaying the results dynamically
With the $results, what you do with the data very much depends on what you want to achieve. At a very basic level, you can do the following to dynamically display a table of the results:
if(mysql_num_rows($results) > 0)
{
$header = false;
print "<table>"
while($row = mysql_fetch_assoc($results))
{
if(!$header)
{
$headings = array_keys($row);
print "<tr>";
for($i=0;$i<count($headings);$i++)
{
print "<th>".htmlspecialchars($headings[$i])."</th>";
}
print "</tr>";
$header = true;
}
print "<tr>";
foreach($row as $value)
{
print "<td>".htmlspecialchars($value)."</td>";
}
print "</tr>";
}
print "</table>"
}
else print "<h1>No Results Found!</h1>";
mysql_free_result($results);
There is still alot not covered in my answer because I can't say what level of detail is required. You will also need to cover things like your connection to MySQL, error handling, formatting of the table...
Update
Hmmm, very interested to know why this has been downvoted. If someone can please explain in comments where I have misinterpreted the question or misguided the user, I would appreciate it.
If you use jQuery the code might look like
<select id="select_id">
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
<script type="text/javascript">
$('#select_id').change(function(e) {
// this code send selected value to the server
$.post('url', {selected_value: this.value}, function(response) {
// handle the server's response
});
});
</script>
On server side take the value from $_POST and make a query. And remember - do not trust to data from client-side. You never know who is over there. Always check incoming data and DO NOT use such constructions
$sql = "SELECT * FROM table_name WHERE name = '{$_POST['selected_value']}'";
because there might be any string including those can drop all databases, clear data and so forth.
Can any one please help me? I am new to php, currently I am trying to use $_POST['item'] to obtain a string (consists of many words) from a dropdown box and then process it. However, when I use $_POST['item'], only first word is returned, the rest of words are missing.
I have a dropdown box, something like:
echo "<form action='process_form.php' method='post'>";
echo "Select an item<br />";
echo "<select name='item' id='item'>";
...
...
...
each item in the dropdown box is a string that has product names like:
dressmaker mannequin size 12
torso mannequin in white color
...
User will then select an item from the dropdown box. When I used $_POST['item'] to obtain this string, I get the first word "dressmaker", all the rests were missing.
How do I get the whole string?
Many thanks in advance.
I am not sure exactly what you are doing but I would do something like this. For this example I assume that the values "dressmaker mannequin size 12" will correspond to the values of the columns in the database to which I will refer to as "colA, colB, colC, and colD", and in addition I assume you have an "ID" column in your database.
Here is the code I would use to generate the select drop-down list:
//$query is the variable storing the result of the mysql_query();
//assumption is that the result-set is non-empty
echo '<select name="item" id="item">\n'; //\n - new line character
//run through the loop to generate the items inside the list
while ($result = mysql_fetch_assoc($query)) {
//note the id - it will be used to find data in the
//database after the POST is complete
//couple of temp variables (not necessary but makes code cleaner)
$database_id = $result["ID"];
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//add option to the select drop-down
echo "<option value=\"$database_id\">$colA $colB $colC $colD</option>\n";
}
echo "</select>";
Now to retrieve the data from the POST. I am including the code Drewdin suggested.
//form was submitted already
//assumption is that the database connection is established
$item_id = mysql_real_escape_string(trim($_POST["item"]));
//Now get the info from the database for this id
//table is "table"
$string = "SELECT * FROM table WHERE ID = $item_id";
$query = mysql_query($string) or die("Could not complete the query: $string");
//assumption here is that the result set is non-empty
$result = mysql_fetch_assoc($query);
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//now you can use the values of colA-D to compute whatever you want
Hope this helps. Using database ids is nice for security plus it makes things more manageable.
Regarding using this blog. You can post comments to the answers people post. If you want however to add something to your question, you can edit your original question and just make sure its obvious what was added.
When the issue is resolved and if any answer helped and you liked it, you can pick it as the final answer by clicking the check mark next to it.
Best of luck
without seeing your select options i think this might help you
if (isset($_POST['submit'])) {
// Grab the output of the select list
$Select_Output = mysqli_real_escape_string( $dbc, trim($_POST['item']));
//What ever else you want to do here...
}
I also would use Miki725's post to make sure your select list is setup correctly
This is how the php gets the values from the HTML select item:
<select name="item" id="item">
<option value="this is option 1">option 1</option>
<option value="this is option 2">option 2</option>
<option value="this is option 4">option 3</option>
...
</select>
Basically you would do something like:
$var = $_POST['item'];
The $var will be the whatever was entered into the "value" of the option tag. So just make sure you have the proper values entered into the value fields.
Hope that helps.