set variable as first option in array php mysql - php

I have a select box being filled in with a mysql query, it functions fine and is selectable. Data changes and works fine.
It currently sorts based on the branch_id column and what I want is the session variable of $branch_id to be the first option of the select box. This is based on the branch selected from a previous page.
This is where I am stuck.
Here is some sample code of the branch dropdown.
This selection then changes a list of users that appears in an options box below this code. It all functions fine, I just need to refine it so the currently selected branch(from a prev page) is the first in the branch dropdown.
If anyone can help I'd really appreciate it.
//get list of allowed Branchs
$AllowBranch = "SELECT branch_id FROM access WHERE userid IN (SELECT id FROM user WHERE username = '{$_SESSION['user']}') ORDER BY branch_id ASC";
$getAllowBranch = mysql_query($AllowBranch);
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<OPTION VALUE = '{$getAllowBranchRow['branch_id']}' "; if($NeedBranch == $getAllowBranchRow['branch_id']) { echo "selected"; } echo "> ".ucwords(strtolower($Namerow['name']));
}
echo "</SELECT>";

Check the source code to see if the selected attribute is put in the right option tag. Also, you forgot to close every <option> tag with a </option>, not sure, but this could also be the problem.

First of all, you have missing tag <select name="<your field name>"> before while loop.
Then you have missing closing tag </option> too. You cannot solve your problem, if you have HTML broken.
So, it should looks like this:
echo '<select name="<your field name>">';
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<option value='" . $getAllowBranchRow['branch_id'] . "'" . $NeedBranch == $getAllowBranchRow['branch_id'] ? " selected" : "" . ">" . ucwords(strtolower($Namerow['name'])) . "</option>";
}
echo "</select>";
What I have done?
Firstly, I fixed your missing HTML tags. Then I just simply used ternary operator to check if branch_id equals to $NeedBrach and if yes, add following string selected and if not, add nothing.
Don't forget to replace <your field name> with your expect select name.
Important final thoughts!
I have to remind using mysql_* is deprecated, you should use mysqli_* or PDO instead with prepared statements.

Related

PHP Select tags problems

I just started learning some PHP and SQL for my uni. I got everything figured out somehow but there have been a few problems. So what I'm doing is getting the values of a 'select' dropdown dynamically from the Database.
$sql = "SELECT catDesc, catID from Categories";
$queryResult = $dbConn->query($sql);
echo '<select name="eventcat" size="1" class="dropdownstyle" id="catevent" required/>';
echo '<option value="choose">Event Category</option>';
while($row=mysqli_fetch_array($queryResult)){
$xx = $row['catDesc'];
$id = $row['catID'];
echo '<option value="' . $id . '">' . $xx . '</option>';
}
So this above piece of code works. However. After the user submits the form. It redirects to a new page. "admin-process.php". I want this page to somehow get the value of the variable "$xx". I know how to get the value by using this method:-
$id = isset($_REQUEST['eventcat']) ? $_REQUEST['eventcat'] : null;
However, this displays the id of the option. Not the main thing that I need. The id and the value differ here. So in short. How do I get the name of the option tag?
How do I get the name of the option tag.
You don't. At least not directly. The only value posted as part of the form is the selected value from that element. In this case your catID value.
That value should uniquely identify the record which was selected. (If it doesn't, that's a different problem.) With that value you can then query the database to get the rest of the information from the uniquely identified record. It may contain one more field, several more fields, joins with other tables, etc. Doesn't really matter what it contains, as long as you can uniquely identify it based on that ID.
So on your next page (admin-process.php) you'd read the posted catID value and use it in a query to your Categories table. That query should return one record, from which you'd display the additional data.

PHP Edit form for MySQL database <option> value is not correct after a fetch

I have a Edit form in php and everything work great. The only issue i have is when i click edit it returns all the data except in the Select drop down. it does not have the chosen category it always shows the first value in the list. But i then can click on the drop down and choose a new category and it works.
//Query the category table
$resultSet = $con->query("SELECT * FROM schedule_category");
<select id="schedule_category" name="schedule_category" class="custom-select">
<?php
while($rows = mysqli_fetch_assoc($resultSet))
{
?>
<option value = "<?php echo($rows['schedule_category'])?>">
<?php echo($rows['schedule_category']) ?>
</option>
<?php
}
?>
</select>
I would like to have it show the correct select option record not the first one in the drop down list. Here is an image of what happens https://imgur.com/a/XVXQ2Sa
You'll need to have your code compare each to the selected value, and add the appropriate keyword:
$previous_selection = // whatever it is, from your data
while($rows = mysqli_fetch_assoc($resultSet))
{
$thisone = $previous_selection == $rows['schedule_category'] ? " selected " : "";
echo '<option value = "';
echo ($rows['schedule_category']) . '"' . $thisone . '>';
echo($rows['schedule_category']) . '</option>';
}
What you're doing here is comparing your previously-selected value to each row, when it matches, the variable $thisone is set to "selected", otherwise it's empty. You then add that to each option line after the value and before the close-tag for the option, and it will add "selected" when the value matches.
Also I personally don't like switching in and out of PHP for no good reason, makes it really difficult to read, hence I echo the various bits of HTML here.
ETA - actually that could be simplified further, if your selection value is the same as the text displayed in the list, there's no need to actually specify the value in the option tag. That is only required when the value is different to the display, for example if you want the user to see your category names, but you want to submit the category ID.

Trying to get value from a select field, which I filled with an SQL query

I come to you in dire need.
What I'm trying to do is to make a form with a dropdown menu, that menu is filled by fetching id's from a table.
<form method="post" action="addWorkExperience.php">
<select name="employerSelection">
<?php
$sql = mysqli_query($conn, "SELECT employer_id FROM employers");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"eID\"> " .$row['employer_id'] . "</option>";
}
?>
</select>
And to my understanding my selected option should be accessible through the $_POST variable like so:
$eValue = $_POST['employerselection'];
or:
$sValue = $_POST['eID'];
These variables would be used in my insert query to write my choice back to the SQL database. However, for some reason it just doesn't. Every other inputfield I trow at it works, except the select field.
Am I missing something?
You have a typo, instead of
$eValue = $_POST['employerselection'];
try
$eValue = $_POST['employerSelection'];
In further situations, you can help yourself by simply using
var_dump($_POST);
that will output all variables that $_POST contains

Assign and return select option dynamically?

I have a form select which is generated based on results returned from a mysql query.
Q1) How do I assign a name identity (integer value) based on the teamID pull out of the database?
Q2) How could I then get the option selected and add it to a php variable which could then be used to update a table based on the users selection?
Below is the code I have so far for creating the dynamic drop down list, which get the results out of the database.
<?php
$data= mysql_query("SELECT * FROM teams
WHERE teamID NOT IN (
SELECT TeamID
FROM leagueInformation
WHERE leagueID = 1
)
") or die(mysql_query());
echo "<select name=\"team\" class=\"col-lg-12\" style=\"padding:10px; background:#e1e1e1;\">\n";
while($info = mysql_fetch_array( $data ))
{
$teamID = $info['teamID'];
echo "<option name=" . $team . " value=" . $teamID . ">" .$info['teamName'] . "</option>";
}
echo "</select>\n";
?>
Q1) How do I assign a name identity (integer value) based on the teamID pull out of the database?
This question is not so clear, but I think this is what you are trying to do?
<?php $data= mysql_query(
"SELECT * FROM teams WHERE teamID NOT IN (
SELECT TeamID
FROM leagueInformation
WHERE leagueID = 1)
") or die(mysql_query());
?>
<form name="teams_form" method="POST">
<select name="team" class="col-lg-12" style="...">
<?php while($info = mysql_fetch_array( $data )): ?>
<option value="<?php echo $info['teamID'] ?>">
<?php echo $info['teamName'] ?>
</option>
<?php endwhile; ?>
</select>
</form>
Q2) How could I then get the option selected and add it to a php variable which could then be used to update a table based on the users selection?
First you will need to wrap your select inside a form (like I did), then you can check the selected value like this:
if(isset($_POST['team']) && !empty['team']){
$selected_team = $_POST['team'];
mysql_query("Do what you want with the selected team");
}
Some notes about your code:
Avoid to use mysql_*, use mysqli_* or PDO, and always prevent SQL injections
<option> tags don't have name properties, and in this case $team is not defined
Embed PHP inside HTML, not HTML in PHP.
Your first question doesn't make sense to me yet, I'll update the answer when it does.
When the user submits the form, you can get the option selected using the $_GET or $_POST (depending your your form's method) variables.
Like this:
$teamId = $_POST['team'];
put everything in a <form/> with an action pointing to the page, and a method (get or post), then in the script get the variable by the <select/> name value reading $_GET or $_POST variables, and I quote the comment about the "name" in option as invalid attribute.

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 ;)

Categories