Posting a value from Dropdown List from PHP div page - php

I'm having an issue in passing a value from a dropdown list that is in a separate PHP file that is being used by jquery.
I ended up getting the values from the dropdown list that isn't posting correctly by using jquery based on the value selected in the first dropdown list. The dropdown list in question is populating correctly, but with the way I have it setup I cannot post the value to the submit PHP page.
I'm pretty sure it has to do with the way I have it setup; however, I'm very new to jquery and was looking for some guidance.
The main PHP Page (the small areas in question)
<select name="department_list" id="department_list" onchange="$('#singleUser').load('get_users.php?nid='+this.value);">
...
<div id="singleUser" class="singleUser">
</div>
The PHP page (get_users) used to fill the values (only the area in question)
echo '<p style="text-align:center">';
echo "
<br />
Select a person to receive the form
<br />";
echo "<select id='userSelect' class='userSelect'>";
if ($id == '50') {
echo "<option value='Done'>Done</option>";
echo "</select>";
}else {
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
}//end else
In the submit page:
if(isset($_POST['userSelect'])){
$givenID = $_POST['userSelect'];
//the rest of my code
I do have the div code above within the form tags and have method="post". All of my other inputs post correctly, so I'm thinking it has to do with the way I have only the div tags within the main page. Again, I'm pretty new to all of this so any ideas or changes that I should make so it posts correctly would be greatly appreciated.

You forgot the name of the select when you write it with php:
change this:
echo "<select id='userSelect' class='userSelect'>";
to
echo "<select id='userSelect' name='userSelect' class='userSelect'>";

i think the error is in the PHP file generating the user select it is missing the name attribute name="userSelect"
echo "<select id='userSelect' class='userSelect'>";
it should be
echo '<select id="userSelect" name="userSelect" class="userSelect">';
every form element with the name attribute gets posted with its value. if you do not enter the name attribute, the value can not be retrieved from the $_POST array. Also have in mind that disabled form inputs also do not get posted.
Edited the PHP quotes. Use Single qutes everyt time you do not need to insert PHP variable into the string. It is ~9 times faster than double quotes ;)

Related

displaying a single row of data in php using pdo

<?php
if (!empty($_POST['modify']) && !empty($_POST['input']) && !empty($_POST['choose'])) {
$val=$_POST['modify'];
$input=$_POST['input'];
echo"<table border=6><tr><th>id_etu</th>
<th>Nom</th><th>Prénom</th><th>email</th>
<th>mot de passe</th><th>Année</th></tr>";
$sql= "SELECT * FROM etudiant WHERE '$val'='$input'";
$sth=$conn->query($sql);
$res= $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($res as $row){
echo "<tr>";
echo "<td>".$row['id_etu']."</td>";
echo "<td>".$row['nom']."</td>";
echo "<td>".$row['prenom']."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['motdepasse']."</td>";
echo "<td>".$row['annee']."</td>";
echo "</tr>";
}
}
?>
Hey everyone, i'm still a beginner in php and using the PDO statement, and right now i'm having trouble displaying a single row of data on a php page. just to put you more in the context.
i have first a form where i choose the field by which i wanna display the row then a input where i type the value of the field then a submit button to send the form, then as a result i should get a table with one row, but instead i get the entire content of the table in the database. Help PLease.

php populate option box from database table

I am writing code to register a new project via a html form. I want to be able to click a dropdown box which pulls the values from a table on the database.
At the moment a dropdown box displays but with no values.
PLEASE NOTE: I am a learning the basics so apologies if this is a simple question/answer scenario.
My code is below, any help is appreciated, I connect to the database via a php include script. The table is called 'customers' and the item I want to list is 'name';-
<?php
$result = mysql_query("SELECT customers FROM name");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
}
echo "</select>";
?>
"The table is called 'customers' and the item I want to list is 'name';" -
Do SELECT name FROM customers instead of SELECT customers FROM name
Using mysql_error() to mysql_query()
would have shown you the error that the table name does not exist.
Plus,
[name] are missing quotes inside them => ['name'] which are being treated as constants.
in
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
as caught and kudos to devdesign
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
However, you are using a deprecated MySQL library. If you are still not getting results, then this could mean that you need to use (and should use) mysqli_ or PDO instead.
Here are a few links on the subject:
mysqli with prepared statements
PDO with prepared statements.
Your code should be. Also note the single quotes within $row['name']. You missed that.
<?php
$result = mysql_query("SELECT name FROM customers");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
}
echo "</select>";
?>

php drop down print selected item

I am trying to print the selected dropdwon item. I have already written the code for dropdown to fetch a column from database.
Now i should print the only the id of selcted dropdown item. i don't know how to make it. please help me, this is my code
<?
$query_name="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`name` ASC";
$result = mysql_query ($query_name);
echo "<select name=category value=''></option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value=$nt[name]>$nt[name]</option>";
}
echo "</select>";
$query_id="SELECT id_cat FROM `fs01_metier_cat`";
$result1 = mysql_query ($query_id);
while($row = mysql_fetch_assoc($result1))
{
echo $row['id_cat'];
}
?>
try this:
while($nt=mysql_fetch_array($result)){
echo "<option value='{$nt['id_cat']}'>{$nt['name']}</option>";
}
with {} php can insert also array values into a string and you should set ' ' around the attribute "value"'s value (alot of values here.. ^^), that the html is w3c conform (i dont know if a browser would take it as correct without them..)
without the { } it would look like that:
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['id_cat']."'>".$nt['name']."</option>";
}
depending on your editor code highlighting might work better in the second case ;)
and about the selected item:
i would suggest you to use jQuery to get the content of the selected item
var selectedId = $('#yourselectid option:selected').attr('value');
and then you can e.g. write it to the document or to a div:
document.write(selectedId);
or
$('#yourDivIdWhereYouWantToPutTheSelectedId').html(selectedId);
important: please note that i changed the value's index to id_cat because then you can handle the options with their id
Since the selected option changes everytime you change the dropdown selection, you can not handle this via php. There are ways to do that without a huge library like jQuery (since they are also just simple Javascript) but they simplify such things alot ;)

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

Keep selections in php generated form after submit (POST)

I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!

Categories