Method for initializing selectmenu to certain value? - php

I have a screen that shows users a list of players and the grades users have given them. By clicking on a button, they can select from a list of players and grade these players themselves.
I want to streamline this process by allowing users to simply click on a player name where it goes to the grading page with the select menu already initialized to the player's name that they just clicked on.
Is there a way to initialize a select menu to a certain value?
Here is the mySQL query:
$query = #mysql_query('SELECT person.firstname, person.lastname, person.id FROM person inner join player ON player.person_id=person.id WHERE player.team_id=' . $homeid . ' ORDER BY lastname asc');
And the code that creates the select menu:
<select name='id'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
}
?>
</select>

of course ,,, The option you want to be selected should contain the attribute selected
if //bla bla this is the one
echo "<option selected=\"selected\" value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
else
echo "<option value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";

if (currentId == $temp['id']) <option selected>...</option>
else <option>...</option>

If you have a value called $id you can:
echo '<option value="'.$temp['id'].'" '.($temp['id'] == $id ? 'selected="selected"' : '').'>'.htmlspecialchars($temp['firstname']).' '.htmlspecialchars($temp['lastname']).'</option>';
Difference:
($temp['id'] == $id ? 'selected="selected"' : '')
The selected attribute on a preselects this value upon loading the page.
I Hope understood your question.

Related

Getting value from populated drop down list

I have populated a drop down list from the database but i dont think the value is being set to the name the user chooses from the drop down as when the form is selected, no value is added to the database.
At the moment, it shows all the names from that table. As i said, i want the value to be the name the user chooses so that when the form is submitted it is added to the database and can be fetched on another page.
<select name="category">
<?php
$sql = mysql_query("SELECT category_Name FROM category");
while ($row = mysql_fetch_array($sql)){
echo '<option value="'.$category_Name.'">' . $row['category_Name'] . "</option>";
}
?>
echo '<option value="'.$category_Name.'">' . $row['category_Name'] . "</option>";
// ^ this var is never set
should be
echo '<option value="'.$row['category_Name'].'">' . $row['category_Name'] . "</option>";
// ^ change this
or you can just have it like this
echo '<option>' . $row['category_Name'] . "</option>";
If value is not set, it just takes the value of the display name.

echo not appearing when selecting a certain value

I have a assessment drop down menu below:
<select name="session" id="sessionsDrop">
<option value="All">All</option>
<option value="2">EOWOW</option>
<option value="34">EOWOW</option>
</select>
<select name="student" id="studentsDrop">
<option value="All">All</option>
<option value="23">Jay Hart</option>
<option value="32">Bubba Wright</option>
</select>
Above is a simple drop down menu. I run a query below to get a selected student's details as well as get the selected assessment details. Now the selected assessment outputs the details fine with no problem, But the echo for selected student option does not work as if the user selects the All option, then echo "<p><strong>Students: </strong>All Students - Total:(" .$selstudentnum . ")</p>" . PHP_EOL;. But the problem is that it does not display this echo if the All option is chosen. In fact it does not display an echo at all if the All option is chosen. I tried both === and == bu can't see what I am doing wrong
$selectedsessionqry = "
SELECT
SessionName, SessionDate, SessionTime
FROM
Session
WHERE
(SessionId = ?)
";
global $mysqli;
$selectedsessionstmt=$mysqli->prepare($selectedsessionqry);
// You only need to call bind_param once
$selectedsessionstmt->bind_param("i",$_POST["session"]);
// get result and assign variables (prefix with db)
$selectedsessionstmt->execute();
$selectedsessionstmt->bind_result($selSessionName,$selSessionDate,$selSessionTime);
while ($selectedsessionstmt->fetch()) {
echo "<p><strong>Assessment: </strong>" . $selSessionName . " - " . date('d-m-Y',strtotime($selSessionDate)) . " - " . date('H:i',strtotime($selSessionTime)) . "</p>" . PHP_EOL;
}
$selectedsessionstmt->close();
$selectedstudentqry = "
SELECT
StudentAlias, StudentForename, StudentSurname
FROM
Student
WHERE
(StudentId = ?)
";
global $mysqli;
$selectedstudentstmt=$mysqli->prepare($selectedstudentqry);
// You only need to call bind_param once
$selectedstudentstmt->bind_param("i",$_POST["student"]);
// get result and assign variables (prefix with db)
$selectedstudentstmt->execute();
$selectedstudentstmt->bind_result($selStudentAlias,$selStudentForename,$selStudentSurname);
$selectedstudentstmt->store_result();
$selstudentnum = $selectedstudentstmt->num_rows();
while ($selectedstudentstmt->fetch()) {
if($_POST["student"] === 'All') {
echo "<p><strong>Students: </strong>All Students - Total:(" .$selstudentnum . ")</p>" . PHP_EOL;
}else{
echo "<p><strong>Students: </strong>" . $selStudentAlias . " - " . $selStudentForename . " " . $selStudentSurname . "</p>" . PHP_EOL;
}
}
I think your condition fails here
$selectedstudentstmt->bind_param("i",$_POST["student"]);
Its expecting integer value but you are sending string.
Don't use $_POST directly in your query.It will cause sql injection attack.
Sanitize the user input before use it in sql queries.
Changes:
Add the below conditions before your query. Once again don't forget to sanitize.
if ($_POST["student"] == 'ALL') {
$where = WHERE (StudentId = ?) ";
} else {
$where = "";
}
$selectedstudentqry = " SELECT StudentAlias, StudentForename, StudentSurname FROM Student $where

options are not getting printed/echoed?

This page generates the option pulled from database . another page brings here the year of joining of students via year_joining . rest of the mysql queries works absolutely fine ( tested )
<?php
include_once("../Include/connectdb.php");
if($_GET['year_join'])
{
$id=$_GET['year_join'];
$result1 = mysql_query("select distinct sub_id from subject_profile where batch='$id'
")or die(mysql_error());
while($subid = mysql_fetch_assoc($result1)){
$result2 = mysql_query("SELECT name FROM `subjects` WHERE `sub_id` LIKE
'$subid[sub_id]'");
$subject=mysql_fetch_assoc($result2);
if($subject[name]!=""){
//print "<OPTION value=".$tmp.'">'.$tmp.'</OPTION>';
//print "<OPTION value='$tmp'>'$tmp'</OPTION>";
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
//echo '<option value="'.$id.'">'.$data.'</option>';
//}
}
}
}
?>
FYI :
//print "<OPTION value=".$tmp.'">'.$tmp.'</OPTION>';
//print "<OPTION value='$tmp'>'$tmp'</OPTION>";
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
//echo '<option value="'.$id.'">'.$data.'</option>';
none of these are working ... :(
with simple echo $tmp it works
but when ever i put as
echo "<option value=";
the result is blank page ...
and when i am echo - ing just the variable its works perfectly fine
echo $tmp;
gives the list of all the subjects ..
For the problem regarding "not displaying output", I believe you have missed a <select> tag enclosing the <option> tags.
As a side note, in the query, change it like this:
"SELECT name FROM `subjects` WHERE `sub_id` LIKE '{$subid[sub_id]}'"
or,
"SELECT name FROM `subjects` WHERE `sub_id` LIKE '" . $subid[sub_id] . "'"
Still it is not safe. You should escape the values and better use a prepared statement using mysqli or PDO
The main problem is as per Akhilesh B Chandran's answer, with a missing <select> tag.
Other than that, there will be a problem when $subject['name'] has a space in it.
The problem is this line:
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
It should be like this:
echo '<option value="'.$subject['name'] . '">' . $subject['name'] . '</option>';
In what you currently have, the browser interprets the result as this:
<option value=insert name here">insert name here</option>
As it is visible, there is a missing quote after value=.
Your quotes don't match up, which is why PHP is failing.
Try changing:
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
to:
echo "<option value=".$subject['name'] . ">" . $subject['name'] . "</option>";
Basically, you start off using a ", and switch partway through to using '

mysql database making drop down menu using data already entered in html/php

I created a database with 3 tables being spusername, splocation, sprecord. spusername has id, splocation_id, lastname, firstname. I want to be able to have a drop down menu that has pulled id, lastname, firstname from the database, and within the pulldown it only shows a list of all the names being lastname,firstname. then once I select a person I have another drop down that has types of training in it. then when I hit submit it will generate a record in another table with the persons id and training record. so when I do a search it will pull up the user and the training records for that person.... I have already created a submit page in a .php that sends lastname, firstname, splocation_id for new users and I think I can create a search that does what I want it to, but I have never made a data entry doing a pulldown that has values generated from the database.
EDIT Code: With help from Vegard's coding I got this, and now it works great after a few trial and errors. Thank You!
Code:
<?php
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(spusername_id,sptraining_id) values ('".mysql_real_escape_string(stripslashes($_REQUEST['spusername_id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['sptraining_id']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into the database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1>Add Training Information To Database</h1><hr>
<br><br>
<form method="post" action="">
<select name="spusername_id">
<option value="default">Select Employee</option>
<?php
include("connectspusers.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY lastname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['lastname'] . ' ' . $row['firstname'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>';
}
?>
</select>
<select name="sptraining_id">
<option value="default">Select Training</option>
<?php
include("connectsptraining.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, trainingtype, level FROM sptraining ORDER BY level ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['trainingtype'] . ' ' . $row['level'] . '">' . $row['trainingtype'] . ' - ' . $row['level'] . '</option>';
}
?>
</select>
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
}
?>
Something like this?
<select name="pulldown1">
<option value="default">Choose an option</option>
<?php
include("connect.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY firstname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . htmlentities($row['id'], ENT_QUOTES) . ' ' . htmlentities($row['lastname'], ENT_QUOTES) . ' ' . htmlentities($row['firstname'], ENT_QUOTES) . '">' . htmlentities($row['lastname'], ENT_QUOTES) . ', ' . htmlentities($row['firstname'], ENT_QUOTES) . '</option>';
}
?>
</select>
<select name="pulldown2">
<option value="default">Choose and option</option>
<?php
$result = mysql_query('SELECT traingtype FROM trainingtable ORDER BY trainingname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['trainingtype'] . '">' . $row['trainingtype'] . '" "' . $row['lastname'] . '</option>';
}
?>
</select>
This will result in two dropdown menus where the first dropdown lists the users last- and firstname separated by a comma+space and the second will list the different types of training. The ID filed is only sendt via the variable, but not displayed to the user.
When pulling the values from the variable in pulldown1, just use explode:
$userdetails = $_POST['pulldown1'];
$values = explode(" " $userdetails);
$ID = $values[0];
$lastname = $values[1];
$firstname = $values[2];
Haven't tested the code so it might need tweaking, and ofcourse you need to change the variable names corresponding to your actual db rownames.
Edit: In your code, you have to use $row and not $row2.
Secondly, instead of this:
<option value='{$id}'>{$lastname},{$firstname}</option>
use this:
<option value="' . $row['id'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>
<select name="id" size="1">
<?php
$result=mysql_query("select * from spusername;");
while($user=mysql_fetch_array($result)) {
echo "<option value=\"".$user['id']."\">".$user['lastname'].", ".$user['firstname']."</option>";
?>
</select>
Go on with always using "id" as a reference to the user and try using post instead of get to send the request(keeps the URL in your user's browser clean).
You build a select in a loop with the data from your database.
example with mysql (did not test):
$query = "select id, lastname, firstname from spusername";
$result = mysql_query($query);
echo "<select>";
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['lastname']. " ". $row['firstname']."</option>";
}
echo "</select>";
EDIT: (response to your edit)
In your code you use $row2 instead of $row
Just an addendum to Vegard's solution:
Single quotes can be a bit tricky with surnames. It really depends on how you're storing the data in your database though.
If you have a surname O'Leary or O'Reilly you might get truncated results as you're building your select loop on the names. Give it a try.
You can fix this issue by using
htmlentities($row['lastname'], ENT_QUOTES) in your select loop

Pre-filling select tags from array

I've got this array:
$profession_type = array(
'Professional Engineers',
'Accountants',
'Insurance Professionals',
'Attorneys',
'Certified Hazardous Materials Managers',
'Safety Professional',
'Industrial Hygienists',
'IT Professionals',
'Human Resource'
);
I am display the contents of the array as the options for the select tag:
<select name="profession_type[]">
<option value=""></option>
EOL;
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
print <<<EOL
</select>
I've never pre-filled a drop down box with dynamic values. The values in $profession_type will change frequently (and will eventually be driven from a table in the db), so I can't do hard code it.
EDIT: Sorry my question was unclear.
The user will select a value from a previous screen (say it's called id) and hit submit.
Before the HTML is rendered to the screen, PHP makes a stored procedure call based on the id they selected.
The values that the stored procedures returns will prefill the "profession_type[]" form field.
I would like the <option value='accountants' selected>Accountants</option> if the stored procedure returns "Accountants" for the value of "profession_type" based on the id.
Is that more clear? Sorry.
Any suggestions?
How about this:
print '<select name="profession_type">';
print '<option value=""></option>';
foreach ($profession_type as $p)
{
if ($p == $chosen_profession)
print "<option value='" . $p . "' selected='selected'>" . $p . "</option>";
else
print "<option value='" . $p . "'>" . $p . "</option>";
}
print '</select>';
This goes in your .php file:
<!-- some HTML here -->
<?php
$profession_type = [result_from_database_query] ?>
<!-- more HTML here -->
<select name="profession_type">
<?php
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
?>
</select>

Categories