PHP Select tags problems - php

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.

Related

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.

Set the default value of a dynamic select drop down list in php

I have a form in an edititem.php page that is used to edit an item. The idea is that from another page, the searchitem.php a user can click edit and is taken to the edititem.php page to edit the selected item. What I'm trying to do is that automatically the default values in the form elements are populated with the values of the item selected to edit (from the searchitem.php) so that the user finds the form populated and only needs to modify the necessary value/s.
I'm passing all the required variables to the edititem.php and I am able to poulate all the input tags but I have a problem with the select tag which is not being set with the desired value. The select tag is being populated dynamically from a mysql database.
<label>Category:</label>
<select name="category">
<?php
$selectedCategory = '';
if (isset($_POST['category'])) {
$selectedCategory = $_POST['category'];
}
$sql_cat = "SELECT id, description FROM category ORDER BY description ASC";
$result_cat = mysqli_query($connection, $sql_cat);
if(mysqli_num_rows($result_cat) > 0){
while($row = mysqli_fetch_assoc($result_cat)){
$selected = '';
if ($selectedCategory == $row['id']) {
$selected = 'selected';
}
echo '<option value="' . htmlspecialchars($row['id']) . '" '.$selected.'>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
With the above code the items in the select tag are being populated dynamically from a table and also if the page is refreshed the selected item is maintained as the selected value.
However I cannot set the default value when I press the edit item from the searchitem.php. The last value in the table is being displayed as default. Any ideas how I can achieve this since I cannot figure out how to do it. Note that all the variables are being passed successfully to the edititem.php page I just need to set the default value of the select drop down list as per the passed variable while keeping the select drop down list dynamic.

set variable as first option in array php mysql

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.

Knowing which <li> item is selected using PHP and mySQL

I have 2 questions. One is if there is any error in this code.
The 2nd question I want to ask is how do you know which <li> item is selected. Right now, the code performs a search in mySQL for all rows that matches city, language and level and returns the results in a list item.
I want it so that when the user clicks on anyone of the list items, it will goes into another page displaying a more detail description by querying the selected list item.
I have a guess, which is for step 2, I also grab the ID (primary key) for each row and somehow keep that stored within the list but not echo.. Would I need to wrap <a> in <form action="XX.php" method="get">?
<?php
//1. Define variables
$find_language = $_GET['find_language'];
$find_level = $_GET['find_level'];
$find_city = $_GET['find_city'];
//2. Perform database query
$results = mysql_query("
SELECT name, city, language, level, language_learn, learn_level FROM user
WHERE city='{$find_city}' && language='{$find_language}' && level='{$find_level}'", $connection)
or die("Database query failed: ". mysql_error());
//3. Use returned data
while ($row = mysql_fetch_array($results)){
echo "<li>";
echo "<a href=\"#result_detail\" data-transition=\"flow\">";
echo "<h3>".$row["name"]."</h3>";
echo "<p>Lives in ".$row["city"]."</p>";
echo "<p>Knows ".$row["level"]." ".$row["language"]."</p>";
echo "<p>Wants to learn ".$row["learn_level"]." ".$row["language_learn"]."</p>";
echo "</a>";
echo "</li>";}
?>
Your code looks alright from what I can see. Does it not work?
One way would be to get the ID through your SQL-query as well and then add the id to the href in your link. Then you can fetch it through the querystring on the other page, to display the proper post depending on which li-element the user clicked on:
echo "<a href=\"details.php?id=". $row["id"] ."\" data-transition=\"flow\">";
Not sure how you mean "somehow keep that stored within the list but not echo" - it wouldn't be possible to store anything in the list, if it is not echoed, as it then wouldn't be sent to the client. You can of course store the id in a data-attribute on the li-element, which won't be displayed to the user. It will however be visible through the source code! Don't know why that should be a problem though?

populate select box with data from mysqltable

How to populate select box with data from mysql table, and then move that value from one page to another.
I did a small coding, and i was able to get all the values from table, but i cant move those value to other page.
$query1="SELECT * FROM seat_no WHERE seatno NOT IN(SELECT seatno FROM check_in_desk)";
$result1 = mysql_query($query1);
<select name="txt_seatno">
<?php
while($nt=mysql_fetch_array($result1))
{
echo "<option value=$nt[id]>$nt[seatno]</option>";
}
</select>
?>
Can you just lookup the values on the page where you need them? If not, you could pass the data as a GET or POST variable, and then use this to generate the select box options on the new page.
There's two ways I can think of;
1) append the value to the url, so it'd be;
echo '' . $nt[seatno] . '';
and in the receiving page, you'd put;
$id = (int) $_GET['id'];
2) Or you could simply use this;
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_select2
(dropdown menu)
(btw; your < /select> should come after ?>)

Categories