This question already has answers here:
create dropdown menu on each loop assign database value to option element
(2 answers)
Closed 9 years ago.
Im working on a page for a sports team where the coach can select his team. What im trying to do is:
1) Print different positions
2) Assign next to position name, players who are ONLY relevant to the
position. (i.e if the positions name is flanker only flankers should
be displayed in the drop-down menu)
My logic for the above problem is:
Assign position names to array called $position Loop over array
querying database, with position having a different value after each loop.
Selected players that match the position gets assigned to an
array called $playerName
Print the $position variable
Create dropdown menu for each position
assign value
from $playername array to the option element in the drop down
menu.
Now there should be different positions with dropdown menus,
next to them, containing player names relevant to position.
//create position array
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="slectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info` WHERE `position` = '$pposition'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) { //create arrays
$id[] = $row['player_id'];
$playerName[] = $row['name'];
$playerLastName[] = $row['surname'];
// print position and open select element
foreach ($position as $playerPosition) {
print $playerPosition;
echo '<select>';
foreach ($playerName as $name) { //assign playername to position element
echo '<option>' . $name;
'</option>';
echo '</select>';
echo '<br />';
} //close assign player nae to position loop
} //end print position and open select loop
} //end while loop
} //end opening for each loop
echo '</form>';
unfortunately for me either my logic is wrong or my code is incorrect. This is the ouput I get: (Note only the name Tendai is displayed in all dropdown meus no other names appear)
If been struggling with this one all morning if someone could point me in the right direction it would be greatly appreciated
(note to modirators the picure above does not contain real names and is only a fictional database)
You can do it like this. the logic is something different
function get_players_by_position($position)
{
$query = "SELECT
`player_id`,
`name`,
`surname`
FROM `player_info`
WHERE `position` = $position
ORDER BY name ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
return $data;
}
foreach($position as $pposition){
$data = get_players_by_position($pposition);
echo $pposition;
echo '<select>';
foreach($data as $row){
echo '<option '.$row['id'].'>' . $row['name'].'</option>';
}
echo '</select>';
echo '<br />';
unset($data);
}
In your original code, you could remove the two foreach loops in the while loop. Use $pposition in place of $playerPosition and your code should work as expected. Here's your code, with my suggested changes, in your procedural style:
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="selectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info`
WHERE `position` = '$pposition'") or die(mysql_error());
echo '<select name="'. $pposition . '">';
while ($row = mysql_fetch_array($result)) {
print $pposition;
echo '<option value="' . $row['player_id'] . '">'.
$row['name'] .' '. $row['surname'].
'</option>';
} //end while loop
echo '</select>';
echo '<br />';
} //end opening for each loop
echo '</form>';
Related
Please forgive me as I am beginner in PHP.
I am trying to populate 2 two column table with inventory information. With my current code, I have the below image:
I would like to have two stores next to each other in this table. i.e Store Number 2 and Store Number 7 on the table row in the table, then Store 10 and 11 on the same row, and so on. Below is the code I am using so far to achieve this:
global $wpdb;
$result = $wpdb->get_results(
$wpdb->prepare( "
SELECT STORE_NAME,REPLACE(STORE_NAME, ' ', '-') as STOREURL, INVENTORY, STORE_NUMBER FROM StoreInventory
WHERE SKU = %s",
$product_sku
)
);
if ($result){
echo '<table class=\'inventory\'>';
foreach($result as $row) {
echo '<tr><td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td></tr>';
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}
The problem I am having is that I am looping through the record set row by row, and adding the data to each row. I have attempted to have a loop inside a loop, which will not give me the correct results.
Is it possible to split the result set into two multi-dimensional arrays and loop through each one separately then add them to the table? Can I call out a specific row with a counter within the loop?
Any advise or direction would be a great help.
A relatively simple approach would be to create a dummy variable to store the column. EX:
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</tr></table>';
Final answer based on ARubiksCube's answer:
if ($result){
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td \' width=\'50%\' ><div><a href=\'https://shopliquornl.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>' . $row->STORE_NAME . '</a><br/>' .$row->INVENTORY. ' on hand</div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}
I can't figure out why my drop down list, which is populated from Mysql, is giving me a number instead of the string value. Below is the code for the drop down list, which properly displays the item names. The problem is when I pull the selected item later I get a number instead of the string item name the user selected.
<select name="product1" class="form-control" id="sel1">
<?php
require('./PHPConnect.php');
$dropdown = array();
$downquery = "SELECT * FROM masterDESC";
$response = #mysqli_query($dbc, $downquery);
if($response){
while(($row = #mysqli_fetch_array($response,MYSQL_ASSOC))){
$dropdown[] = $row['DESCRIPTION'];
}
}
foreach($dropdown as $key => $value){
echo '<option value=' . $key . '>' . $value . '</option>';
}
echo "</select>";
mysqli_close($dbc);
?>
Here is the code later used to pull the selected item.
$product1 = $_POST['product1'];
Any thoughts?
It is spitting put the index number because you are retrieving an array which is just the description values (from this "$dropdown[] = $row['DESCRIPTION'];" you have returned from the DB and when there are no keys listed - the array index is the $key - therefore the number
you need to change the following
foreach($dropdown as $key => $value){
echo '<option value=' . $key . '>' . $value . '</option>';
}
to this and set the value of the option to the same as the displayed content (or leave it with the number and reference it later as $dropdown[index].
foreach($dropdown as $value){
echo '<option value="' . $value. '">' . $value . '</option>';
}
Never mind I got it figured out. It was the key value pair on the foreach. It was necessary for a similar drop down I created in the past but didn't work here. I just got rid of the foreach and it worked.
<select name="product1" class="form-control" id="sel1">
<?php
require('./PHPConnect.php');
//$dropdown = array();
$downquery = "SELECT *
FROM masterDESC";
$response = #mysqli_query($dbc, $downquery);
if($response){
while(($row = #mysqli_fetch_array($response,MYSQL_ASSOC))){
$dropdown = "<option value=\"{$row['DESCRIPTION']}\">
{$row['DESCRIPTION']}</option>\n";
echo $dropdown;
}
}
echo "</select>";
mysqli_close($dbc);
?>
i already have a while loop that displays select inputs in my form depending on how many passengers the user is booking. Each drop down was supposed to show all data from a column in my database. The problem is that only the first drop down displays the data i fetched which is seats 1 to 30.
Query to get the airline id of the current flight
$result = mysqli_query($conn,"select * from flight_seat_status where flight_number = '$_SESSION[departure]'");
Variables i used to start the counting in the loop
$print = 1; $name = 0;
My while loop with the problem
echo "<h1 class='adminContent_h1'>Please choose a seat</h1>";
while($print <= $_SESSION['passengers']){
echo "<label style = 'width:170px;'>". $_SESSION['firstname'][$name]."'s Seat</label>";
echo "<select class = 'content_dropdown' style = 'width:15%; margin-bottom:20px;' name = 'passengers[]'>";
while($row = mysqli_fetch_assoc($result)){
echo "<option value='".$row['seat_id']."'>".$row['seat_number']."</option>";
}
echo "</select><br>";
$print++;
$name++;
}
it is able to print out a number of drop downs depending on the user but only the first drop down contains the data.
what is wrong with my code? please explain
You have to set the pointer back to 0 for using the result again
// set the pointer back to the beginning
mysqli_data_seek($result, 0);
while($row = mysqli_fetch_assoc($result)){
// do whatever here...
}
Please use below code. All the seats records you have to fetch once outside passenger loop and store in another array and then you have to use seats array inside the passenger loop each time.
echo "<h1 class='adminContent_h1'>Please choose a seat</h1>";
$seats = [];
while($row = mysqli_fetch_assoc($result)){
$seats[] = $row;
}
while($print <= $_SESSION['passengers']){
echo "<label style = 'width:170px;'>". $_SESSION['firstname'][$name]."'s Seat</label>";
echo "<select class = 'content_dropdown' style = 'width:15%; margin-bottom:20px;' name = 'passengers[]'>";
foreach($seats as $res_seat){
echo "<option value='".$res_seat['seat_id']."'>".$res_seat['seat_number']."</option>";
}
echo "</select><br>";
$print++;
$name++;
}
Im working on a page for a sports team where the coach can select his team. What im trying to do is:
1) Print different positions
2) Assign next to position name, players who are ONLY relevant to the position. (i.e if the positions name is flanker only flankers should be displayed in the drop-down menu)
My logic for the above problem is:
Assign position names to array called $position Loop over array
querying database, with position having a different value after each
loop.
Selected players that match the position gets assigned to an array
called $playerName
Print the $position variable
Create dropdown menu for each position
assign value from $playername array to the option element in the drop
down menu.
Now there should be different positions with dropdown menus, next to
them, containing player names relevant to position.
//create position array
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="slectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info` WHERE `position` = '$pposition'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) { //create arrays
$id[] = $row['player_id'];
$playerName[] = $row['name'];
$playerLastName[] = $row['surname'];
// print position and open select element
foreach ($position as $playerPosition) {
print $playerPosition;
echo '<select>';
foreach ($playerName as $name) { //assign playername to position element
echo '<option>' . $name;
'</option>';
echo '</select>';
echo '<br />';
} //close assign player nae to position loop
} //end print position and open select loop
} //end while loop
} //end opening for each loop
echo '</form>';
unfortunately for me either my logic is wrong or my code is incorrect. This is the ouput I get: (Note only the name Tendai is displayed in all dropdown meus no other names appear)
Ive been struggling with this one all morning if someone could point me in the right direction it would be greatly appreciated
(note to modirators the picure above does not contain real names and is only a fictional database)
This could be your problem
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info` WHERE `position` = '$pposition'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) { //create arrays
$id[] = $row['player_id'];
$playerName[] = $row['name'];
$playerLastName[] = $row['surname'];
// print position and open select element
print $pposition;
echo '<select>';
foreach ($playerName as $name) { //assign playername to position element
echo '<option>' . $name;
'</option>';
echo '</select>';
echo '<br />';
} //close assign player nae to position loop
} //end while loop
} //end opening for each lo
I have removed foreach ($position as $playerPosition) {
You can do it like this. the logic is something different
function get_players_by_position($position)
{
$query = "SELECT
`player_id`,
`name`,
`surname`
FROM `player_info`
WHERE `position` = $position
ORDER BY name ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
return $data;
}
foreach($position as $pposition){
$data = get_players_by_position($pposition);
echo $pposition;
echo '<select>';
foreach($data as $row){
echo '<option '.$row['id'].'>' . $row['name'].'</option>';
}
echo '</select>';
echo '<br />';
unset($data);
}
What I'd like is to create a new unordered list for each new value in a mysql result column.
My query looks like this and i'm throwing it into a data array:
$connection = dbconnect();
$getusers = "SELECT users.usr_id, users.usr_firstname, users.usr_lastname, user_groups.group_name FROM users INNER JOIN user_groups ON users.usr_group = user_groups.group_id ORDER BY group_name ASC, users.usr_firstname ASC, users.usr_lastname ASC";
$result = mysql_query($getusers);
$data_array = array();
while($data = mysql_fetch_array($result)){
$data_array[] = $data;
}
Now I need to display that data so that each new user_group is an unordered list, and each row with that same group, comes up as a list item of that unordered list.
it's very similar to this question ( PHP/MySQL Query Results ), but i'm having trouble getting the closing ul's in the right place. Here's my code for outputting, though I know it's wrong because the li's aren't really children of the ul's.
$previousgroup = "";
foreach($data_array as $users){
if($users['group_name'] != $previousgroup){
echo "<ul class=\"group\">" . $users['group_name'] . "</ul>";
}
else{
echo "<li id=\"m" . $users['usr_id'] . "\"><h4>" . $users['usr_firstname'] . " " . $users['usr_lastname'] . ", " . $users['cred_name'] . "</h4></li>";
}
}
Is there a more efficient way of doing this? Thanks for your help.
You could change the while loop this way:
$data_array = array();
while($data = mysql_fetch_array($result)){
$data_array[$data['group_name']][] = $data;
}
and you would get an array that contains your group_name's as index of other arrays which contain your data. To create the list, you could do the following:
<ul>
<?php
foreach ($data_array as $temp_key => $temp_array)
{
?>
<li>
<?php echo $temp_key; ?>
<ul>
<?php
foreach ($temp_array as $datum)
{
echo ("<li>" . $datum['usr_firstname'] . "</li>";
}
?>
</ul>
</li>
<?php
}
?>
</ul>
Hope it works for you
if($users['group_name'] != $previousgroup){
echo "</ul><ul class=\"group\"><li>" . $users['group_name'] . "</li>";
}
echo "<li id=\"m" . $users['usr_id'] . "\"><h4>" . $users['usr_firstname'] . " " . $users['usr_lastname'] . ", " . $users['cred_name'] . "</h4></li>";
The code in your loop should look like this, and you need to open and close a <ul> from outside the loop.
echo '<ul>';
foreach () { // here is the loop }
echo '</ul>';
THis is doing it the "dirty" way with printing out as you go, at least.
The way I would do it would be to build a 2D array indexed first by group_name and then by user ID. It would mean making two passes at the data as a second loop would be needed to display the data, but generally speaking you're not going to feel the difference.