(PHP) Categorize into an html opgroup based on mysql value - php

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>";
}

Related

Get selected values in multiselect form field

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.

Dynamic Optgroup in PHP

This is my current SQL Table I'm using to grab data for my php dropdown. The main goal of this is to turn this into a dropdown that has an optgroup with the members below and so on...
+-----------+------------+-----------+
| GroupName | MemberName | ValueName |
+-----------+------------+-----------+
| 1st Team | Joe Bob | Joe |
| 1st Team | Catherine | Kat |
| 2nd Team | Tommy | Tom |
| 3rd Team | John Razks | John |
+-----------+------------+-----------+
Table name: Members
Basically at the end result is such of the code below. It will be a dropdown with an optgroup called "1st Team" and have the members below ect. for 2nd Team and 3rd Team and so on.
<optgroup class="1st Team">
<option value="Joe">Joe Bob</option>
<option value="Kat">Catherine</option>
</optgroup>
<optgroup class="2nd Team">
<option value="Tom">Tommy</option>
</optgroup>
<optgroup class="3rd Team">
<option value="John">John Razks</option>
</optgroup>
Right now, this is how I get information from my SQL table. This works fine, but if I want to add a new GroupName then I would have to add a new code to my main page and I don't want to do that.
Trying make it dynamic so if the SQL table gets updated with a new GroupName, then a new optgroup class will appear in the dropdown and the members will be below.
<optgroup class="1st Team">
<?php
$conn = mysqli_connect("#connect_to_sql");
if(!$conn){
die("Connection Failed".myslqi_connect_error());
}
$result = mysqli_query($conn, "SELECT distinct MemberName from Members where GroupName = "1st Team" order by MemberName ASC");
while ($row = mysqli_fetch_assoc($result)){
unset($membername, $groupname);
$groupname = $row['GroupName'];
$membername = $row['MemberName'];
echo '<option value="'.$membername.'">'.$membername.'</option>';
}
?>
</optgroup>
I'm not positive at all on what to do. I've looked at other people's examples, but not sure how to approach this step.
First get all records from the database. create an array with keys as group name. Loop the new array to generate the desired output.
// query to get all records from database table
$result = mysqli_query($conn, "SELECT distinct MemberName,GroupName,ValueName from Members order by MemberName ASC");
while ($row = mysqli_fetch_assoc($result)){
// generate an array with keys as group name
$array[$row['GroupName']][] = $row;
}
// loop the array to create optgroup
foreach($array as $key=>$value){
// check if its an array
if(is_array($value)){
// create optgroup for each groupname
echo "<optgroup class='".$key."'>";
foreach($value as $k=>$v){
echo "<option value='".$v['membername']."'>'".$v['membername']."'</option>";
}
echo "</optgroup>";
}
}
I have not tested this but sure this will help you. And you can make improvements.
It's not the most elegant way, but you could build your group this way, what it's doing is checking the name of the group and changes that to a new optgroup each time the name changes, the $first var is just there so it doesn't add a closing tag the first time around.
I'm sure you can improve on this, but it should get you going.
It does kind of rely on a consistent naming convention for the group name, so as I say, I'm sure you could improve on it. I've also not included the connection checks as you've done that already in your example
$result = mysqli_query($conn, "SELECT * FROM Members ORDER BY GroupName");
$groupName = '';
$first = true;
echo '<select>';
while ($row = mysqli_fetch_assoc($result)){
if ($row['GroupName'] != $groupName) {
$groupName = $row['GroupName']; // Just set the new group name
if (!$first) { // Add a closing tag when we change the group, but only if we're not in the first loop
echo '</optgroup>';
} else {
$first = false; // Make sure we don't close the tag first time, but do after the first loop
}
echo '<optgroup label="' . $groupName . '">';
}
// We want to echo the options every loop so it's outside the if condition
echo '<option value="' . $row['MemberName'] . '">' . $row['ValueName'] . '</option>';
}
echo '</select>';

output sql query in php

I'm a noob at php so I need a bit of help. I have a table with a list of hotels, the columns are
name | address | city | stars | price
so far I've made a dynamic drop-down menu where the user selects a city from the table, this is shown in the code below:
<?php
connection stuff blah blah
?>
<?php
$sql = "SELECT city FROM hotels";
$result_db = $db->query($sql);
if (!$result_db) {
echo $db->error . ' Error perform query!';
} else {
echo '<select name="value">';
echo '<option value="">-Select from below-</option>';
while ($row = $result_db->fetch_object()) {
echo '<option city="' . $row->city . '">';
echo $row->city;
echo '</option>';
}
echo '</select>';
}
?>
How would I now create a table where all the details of hotels in the selected city are outputted? I'm assuming I need another sql query, arrays (perhaps?) which then I echo into a table? :S But I have no idea how to.....
you need to use jquery to add event to your dropdown second in your table you should have an ID field..
You're table should be
Id | name | address | city | stars | price
next you need to create a query that will fetch the id and name fields and put it on a dropdown.
next you need to use jquery to add event to dropdown.
$(function() {
$("#hotel").change(function() {
});
})

PHP and sql diplay item

I'm facing some problem regarding to display data from sql.
I store my data into 2 table: table student and table company.
table student
{ id, name, company_code, fac_staff_id }
table company
{id, company_name, company_state}
I'm trying to create a table shown as below.
State A
company A
student 1
student 2
company B
student 3
student 4
State B
company C
student 5
company D
student 6
student 7
student 8
I tried create a table similar as above structure but just want classify all the student based on there company_state. The output just display only one state and put all student into that state.
$querysel = "SELECT DISTINCT c.company_state,s.fac_staff_id FROM tblcompany
c, tblstudent s WHERE c.id = s.company_code " ;
$resultsel = mysql_query($querysel, $connection);
$querystdsel = "SELECT s.name,c.company_state FROM tblcompany c,
tblstudent s WHERE c.id = s.company_code " ;
$resultstdsel = mysql_query($querystdsel, $connection);
while($rowsel =mysql_fetch_array($resultsel)){
if ($rowsel['fac_staff_id'] == NULL){
echo $rowsel['company_state'];
while($rowstdsel =mysql_fetch_array($resultstdsel)){
if($rowstdsel['company_state']=$rowsel['company_state']){
echo $rowstdsel['name'];
}
}
}
}
Hope someone can tell me way to create a table like above or any alternative ways because i'm still poor in php and mysql. thank you
You should join your statements to have only one result, where every row looks like this with "order by company_state, company_name"
state | company | student
A | A | student1
A | A | student2
A | B | student3
....
In your php you then use lists to get your structure. Something like this: Just written down and no nice, clean, functional code!
<?php
$rows = mysqli_fetch_array($result);
echo "<ul>";
$lastcompany = "";
$laststate = "";
foreach($rows as $row)
{
if(($laststate == "") or ($laststate != $row['state']))
{
// New Item on mainlist: states
if($laststate != $row['state'])
{ // close previous lists (students, companies)
echo "</ul></ul></li>";
}
echo "<li>".$row['state'];
}
if(($lastcompany == "") or ($lastcompany != $row['company']))
{
// New Item on mainlist: companies
if($lastcompany != $row['company'])
{ // close previous (students) list
echo "</ul></li>";
}
echo "<li>".$row['company'];
}
// New student entry
echo "<li>".$row['company']."</li>";
// Redmine company and state for next iteration
$lastcompany = $row['company'];
$laststate = $row['state'];
}
// After all close all lists
echo "</ul></ul></ul>";
?>

dropdown from two tables, php mysql

Say I have the two following tables:
country_table:
---------------------------------
|ID|country_code|country_name |
|01|CA |Canada |
|02|US |United States |
---------------------------------
user_table:
----------------------------------------------
|id|user_id|country_code|email_address |
|01|oswalsh|CA |blah#hotmail.com |
|02|jlong |US |blah2#hotmail.com |
----------------------------------------------
I am creating my user signup/edit account forms, and have a drop down for country. Originally I had simply stored the country_name in the user_table instead of using a country_code, however I have also decided to implement a map script...which is a massive mess of javascript files which make use of the country_code.
Thus I created the country_table so I could match the country_code and the country_name so I could map user interactions...However I am not sure how to go about creating the sql statement for the drop down.
What I have so far:
<?php
include ('../../connect.php');
$account_panel = mysql_query("SELECT * FROM user_table WHERE id=1")
or die(mysql_error());
while($row1 = mysql_fetch_array( $account_panel ))
{
?>
<select name="event_country" id="event_country" required />
<option selected="selected" value="<?php echo $row1['user_country']; ?>"><?php echo $row1['user_country']; ?></option>
<?php
$countries = mysql_query("SELECT * FROM country_table")
or die(mysql_error());
while($row = mysql_fetch_array( $countries ))
{
echo "<option value='". $row['value'] ."'>". $row['name'] ."</option>";
}
echo "</select>";
?>
<?php
}
mysql_close($connection);
?>
So as you should be able to see from above what is happening, is that the list is populated from the country_table, but I am trying to get the selected value from the user table. This does seem to work, but my problem is that the country code is what is stored and being displayed. So say I am grabbing the info for oswalsh...me...the country returned is CA, and I would like it to display Canada.
If I understood you right, you need to familiarize yourself with SQL Joins
To join those two tables and get the country_name along with the user data from the user_table, you'd need an SQL statement like this:
SELECT ut.*, ct.country_name
FROM user_table ut
INNER JOIN country_table ct
ON ut.country_code = ct.country_code
In your case, this would result in the following:
1 oswalsh CA blah#hotmail.com Canada
2 jlong US blah2#hotmail.com United States
Also, you should consider using mysqli_ and stop using mysql_ functions. Here is a discussion on this topic on SA.

Categories