I'm updating a PHP form field from a dropdown (single value selected) to a multiselect (multiple values selected).
I have 2 DB tables, one where the complete list of team members reside, and the other where the selected team members reside.
On the PHP page, I want to get the values from the full team members table and show the full list as a multiselect form field.
Then I want to be able to get the values from the selected team member table and have them show as selected options in the full multiselect list mentioned above.
Any idea on how I would accomplish this?
Here's my code, although right now it just returns the full team member list without the selected values.
$query = "SELECT walkername FROM Team_Management WHERE active=1 ORDER BY walkername ASC";
$stmt = $mysqli->prepare($query) or die ("Couldn't execute query: ".mysqli_error($mysqli));
$stmt->execute();
$stmt->bind_result($walkers);
echo "<div class='form-group'>";
echo "<label class='col-lg-3 control-label' for='Walkers'>Walkers:</label>";
echo "<div class='col-lg-5'>";
echo "<select multiple class='form-control' name='walkers[]' id='Walkers'>";
while ($stmt->fetch()) {
echo "<option value='$walkers'>$walkers</option>";
}
echo "</select>";
echo "</div>";
echo "</div>";
$stmt->close();
** UPDATED **
So one thing that I should've added, is that the SELECTED_TEAM_MEMBERS field is a comma separated field.
TEAM_MANAGEMENT table
id || walkername
1 || John
2 || Kate
SELECTED_TEAM_MEMBER table
cid || walkers
1 | John,Ray,Kate
2 | Kate,Matt,Joe
In addition, each group in the walkers field in the SELECTED_TEAM_MEMBER table is tied to a unique client id (cid).
So how can I identify the selected walkers from the complete list in the TEAM_MANAGEMENT table by unique client id.
You can get the list of your selected user with a boolean in your SQL request
SELECT walkername,
CASE WHEN **selected_team_members_name** > '' THEN '1' ELSE '0' END as is_selected
FROM Team_Management
LEFT OUTER JOIN **SELECTED_TEAM_MEMBERS** ON **selected_team_members_name** = walkername
WHERE active=1
ORDER BY walkername ASC
With selected_team_members_name the name of the column in your table and SELECTED_TEAM_MEMBERS the name of your table
And now $walker is as array with 2 key: walkername and is_selected
And after you can try a if to put them the attribute 'selected' when you write your 'option' tag
while ($stmt->fetch())
{
$selected = "";
if($walkers['is_selected'] == '1'){ //If your walker is selected
$selected = "selected";
}
echo "<option ".$selected." value=".$walkers['walkername'].">".$walkers['walkername']."</option>";
}
I may not have understand the context but i hope i helped you.
Related
I am busy making a multi-shop shopping site like amazon.com, ebay, carousell.com etc...
Now when users create a listing I made a custom fields system that get the custom fields from a mysql table then outputs them into the form.
The Code:
Okay so first this is the listings table:
ID
list_title
list_brand
seller_id
1
Two sticks
Mr Sticks
1012
Then we have listings_meta which is where I store the custom fields like for a pillow it would be type of filling or for a stick it would be color of stick:
ID
listing_id
meta_key
meta_value
1
1
stick_color
brown
Now the meta key comes from a database table called [form_fields] which is linked the the categories like this
[form_fields]:
ID
meta_key
type
meta_link
1
stick_color
select
0
2
stick_length
input
0
3
rock_weight
input
0
4
brown
option
1
5
blue
option
1
And the category table[cats]:
ID
category
4
Sticks
5
Stones
Link custom fields and categories[cat_meta]:
ID
meta_id
cat_id
1
1
4
2
2
4
3
3
5
So now that you know how the items link with each other lets dive into the PHP code:
Now fist when a user clicks create product that will be given a popup asking which category they want to list the product thats done with a simple select query then they will be redirected to a new page called new_product.php?cat=[id of category from database ID]
new_product.php?cat=4
Now some of the fields are the same for all products they are the ones in listings table
But for custom fields its a bit more complex
:
<input type="text" name="list_title " placeholder="Title">
</br>
<input type="text" name="list_brand " placeholder="Brand">
</br>
<?php //get custom fields from custom_inputs table
//query the database for fields id and
$stmt = $conn->prepare("SELECT `meta_id ` FROM `cat_meta` WHERE `cat_id` = ?");
$stmt->bind_param("i", $_GET['cat']);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row_get = $stmt_results->fetch_assoc()){
$field_id[] = $row_get['meta_id ']; //store all id's in array
}
if(empty($field_id)){ //no custom field found in database
return 0;
}else{
foreach($field_id as $field_id){ //loop ID's to get multiple
$stmt = $conn->prepare("SELECT `meta_key `, `type ` FROM `form_fields` WHERE `ID` = ?");
$stmt->bind_param("i", $field_id);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row = $stmt_results->fetch_assoc()){
$field_name[] = $row['meta_key']; //get key aka title
$field_type[] = $row['type']; //get the type of input
}
}
}
foreach ($field_name as $index => $field) { //combine the type and meta key
$type = $field_type[$index];
if($type === "select"){ //field type is a select
echo '</br><select name="body['.$field.']">';
echo '<option selected Disabled value="">Select Option</option>';
//get options from `form_fields` linked to this meta_id
$stmt = $conn->prepare("SELECT `meta_key` FROM `form_fields` WHERE `meta_linked` = ? AND `field_type` = 'option'");
$stmt->bind_param("s", $field);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row = $stmt_results->fetch_assoc()){
echo '<option value='.$row['meta_key '].'>'.$row['meta_key'].'</option>';
}
echo '</select>';
}
if($type === "input"){ //field type is a user input
echo "<input name='body[$field]' placeholder='$field'>";
}
}
?>
Yes I know the code is very messy but I will clean it up before it is pushed but my issue is I feel like this seems over-complex/not efficient, Can anyone recommend a better way to build custom fields based on the category that was selected.
Also i do not include a lot of html and other php processing code as i dont think it needs to be included but if you need more info i will give it :)
I have two tables. Enrollment and Product. I want to list Product on a <select>.
Within this <select>, I only want certain Product items to appear, whereby the condition is to read from Enrollment table's ProductID which is a foreign key to Product table.
How does one exclude certain results in a <select> that had already existed in a different table?
<?php
$sql = 'SELECT * FROM product ORDER BY ProductID ASC';
$result_select = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($result_select))
$rows[] = $row;
echo "<div class=\"spanstyle\">Add course/product:<select name='add_product'>";
echo "<option selected>Choose here</option>";
foreach ($rows as $row) {
echo "<option value='" . $row['ProductID']."'>" . $row['ProductName']."</option>";
}
echo "</select></div>";
$select1 = $_POST['add_product'];
if (!strpos($select1, 'Choose here')) {
$sql3="INSERT into enrollment (StudentID, ProductID) VALUES ($StudentID, $select1)";
mysql_query($sql3);
}
?>
First reaction is that you need to modify your SQL query here, not the PHP loop. Something like (and this is a quick first shot so don't trust it without testing)
SELECT * FROM product WHERE ProductID NOT IN (SELECT ProductID from enrollments) ORDER BY ProductID ASC
This would exclude any row in product whose ProductID also appears in the enrollments table.
I want to edit the employees's information in a dropdown list, I have two database tables where there is a shared field : in table1, I have many fields and one of them is the employee Position which is a number. in table2 I have two fields: EmpPos(which is equal to Position in table1) and PosName. Now, in the dropdown list, when I add a new employee I fill the list with PosName from table2 but store Position number in table1. the problem is in the edit form, I print all employee's info from table1 in the form to edit them but I don't know how to select employee's PosName from its associated Position in the dropdown list here is my code:
echo" <b>Position: </b> <select name='Position' >";
$sql="SELECT * FROM table1 LEFT JOIN table2 ON table1.Position = table2.EmpPos";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$PosName=$row["PosName"];
$Id=$row['EmpPos'];
echo" <option name= '$PosName' value='$PosName' ' . (($Id==$Position) ? 'selected' : '') . '>$PosName</option>";
}
}
Thank You!
Basically I have a database with 66 bible books; some from old testament some from new. The bname value is the NAME of the book, while bsect has a value of O or N(new or old), how can I make my dropdown box dynamically display a book into an old or new optgroup based on whether its' bsect is O or N? My teacher said I have to make some array, but i have no idea how to do it. Any thoughts?
My database sample:
+-----------+-------+
| bname | bsect |
+-----------+-------+
| Genesis | O |
| Exodus | O |
| Leviticus | O |
+-----------+-------+
I don't want to have to rely on manually setting opgroups based on the NUMBER OF THE ENTRY, I want it to be dynamic based on value of bsect.
Right now I just have the following query with a select dropdown which puts the book into old or new based on its record number, but It will break if more books were to be added
$query = $mysqli->query("select distinct bname as Name from kjv");
?>
<select name="book">
<?php
$i=1;
while($option = $query->fetch_object()){
if($i==1) echo "<optgroup label='Old Testament'>";
else if($i==40) echo "<optgroup label='New Testament'>";
echo "<option value='$i'>".$option->Name."</option>";
$i++;
}
?>
Simply order by bsect and display different optgroups dynamically
<?php
$query = $mysqli->query("SELECT DISTINCT bsect, bname AS Name FROM kjv ORDER BY bsect");
?>
<select name="book">
<?php
$i = 1;
$bsect = "";
while($option = $query->fetch_object()){
if($bsect != $option->bsect) {
$bsect = $option->bsect;
echo "<optgroup label='{$bsect}'>";
}
else if($i==40) echo "<optgroup label='New Testament'>";
echo "<option value='$i'>".$option->Name."</option>";
$i++;
}
?>
Of course, then your books may be out of order. So what you would want to do is add a book-order column (border) that stores a number defining how to order the books in a given group, e.g.
ALTER TABLE kjy
ADD COLUMN border INT U?NSIGNED NOT NULL DEFAULT 0;
Then you can update the data to have the proper book order and do a query like this:
SELECT DISTINCT bsect, bname AS Name FROM kjv ORDER BY bsect, border;
Of course, this being the Bible, you aren't going to be adding books, so you can probably just define a static Book ID that defines the ordinality of each book. Then you could just sort by ID and know that "Old" and "New" books are coming out in the right order.
ALTER TABLE kjy
ADD COLUMN id INT UNSIGNED NOT NULL PRIMARY KEY BEFORE (bname);
This is how you can create 2 arrays in php,
$query = $mysqli->query("select distinct bname,bsect from kjv");
while($option = $query->fetch_object()){
if ($option->bsect == 'O'){
$books_old[] = $option->bname;
} elseif ($option->bsect == 'N'){
$books_new[] = $option->bname;
} else {
# Error collection - bsect not 'O' or 'N'
}
}
now you have 2 arrays which are lists of books; $books_old and $books_new.
I'd use the name as the value rather than an arbitrary index;
echo "<optgroup label='Old Testament'>";
foreach($books_old as $this_book){
echo "<option value=\"$this_book\">$this_book</option>";
}
echo "<optgroup label='New Testament'>";
foreach($books_new as $this_book){
echo "<option value=\"$this_book\">$this_book</option>";
}
I am using the follow bit below. I am first querying the db to see all available options but this is for an edit form so i want the drop down to show the previously selected value so i did another query and got the selection. When i do it the way i have it below it will keep repeating the previously selected selection after each available option. HOw to fix this?
<option>Select Sales rep</option>
<?php
$query="select agent_id, agent_name from agent_names where agent_id='$ad'
order by agent_name asc";
$result=mysql_query($query);
while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
echo "<option value=\"".$previousname."\">".$previousselection."</option>
<option value=\"".$agent_id."\">".$agent_name."</option>";
}
?>
Just check if $agent_id equals $previousname (perhaps you mean $previousid?) and echo selected="selected" if so:
while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
$selected = $agent_id == $previousname;
echo "<option " . ($selected ? "selected=\"selected\"" : "") . " value=\"".$agent_id."\">".$agent_name."</option>";
}
Another option is to output the previous selected item before your while loop, and exclude it in your sql query.
you should take the previos selection out of the while.. like this:
<?php
$query="select agent_id, agent_name from agent_names where agent_id='$ad'
order by agent_name asc";
$result=mysql_query($query);
echo "<option value=\"".$previousname."\">".$previousselection."</option>";
while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
echo "<option value=\"".$agent_id."\">".$agent_name."</option>";
}
?>
and maybe even add an if so it wont repeat it self:
$query="select agent_id, agent_name from agent_names where agent_id='$ad'
order by agent_name asc";
$result=mysql_query($query);
echo "<option value=\"".$previousname."\">".$previousselection."</option>";
while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
if ($agent_id != $previousname) {
echo "<option value=\"".$agent_id."\">".$agent_name."</option>";
}
}
?>
You can force MySQL to return your desired result first in the list like this:
$query = "SELECT agent_id, agent_name FROM agent_names WHERE agent_id='$ad'
ORDER BY agent_id = '{$previousname}' DESC, agent_name ASC";
This tells MySQL first to sort by agent_id matching previous selection (i.e. it will be 1 for the previously selected record and 0 for all others, hence sorting by it DESC makes it first in the list. And since all others will have this fields equal to 0, they will be sorted by second field, which is agent_name ASC