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.
Related
I am learning PHP and I want to know how to do an inner loop or nested loop with records in PHP. I will appreciate if somebody explains me how to do this type of loop in PHP.
I have this table in MySQL
[]
I just want to create a report table in PHP that looks like this:
So far, I know how to do a current loop with the code below but how could I do in the same loop and inner loop to show dishes like table above. I know how to create the format (table, spaces, etc) I just need the PHP logic to do this in the best way.
<?php
do { ?>
Table in here
<?php } while ($selecc = mysqli_fetch_assoc($conmenu)); ?>
The clean/direct approach should be something like this:
SELECT Client, Option, GROUP_CONCAT(Dish SEPARATOR ', ')
FROM table_name
GROUP BY Client, Option
Then with your data already grouped and glued together, just print your strings in a single loop of the result set.
Using a do {} while () is of no benefit here.
Here's an untested snippet...
if ($conmenu) {
echo '<table>';
echo '<tr><td>Client</td><td>Option</td><td>Dishes</td></tr>';
while ($row = mysqli_fetch_assoc($conmenu)) {
echo '<tr><td>' , implode('</td><td>', $row) , '</td></tr>';
}
echo '</table>';
}
For the record:
The maximum permitted result length in bytes for the GROUP_CONCAT() function. The default is 1024.
https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_group_concat_max_len
Also, $conmenu is iterable, so you could use a foreach instead of a while loop.
foreach ($conmenu as $row) { ...
If you want to do it the hard way...
SELECT Client, Option, Dish
FROM table_name
ORDER BY Client, Option
Then... (untested)
if ($conmenu) {
echo '<table>';
echo '<tr><td>Client</td><td>Option</td><td>Dishes</td></tr>';
$group = null;
foreach ($conmenu as $row) {
if ($group !== $row['Client'] . '_' . $row['Option']) {
if ($group !== null) {
echo '</td></tr>';
}
echo '<tr><td>' , implode('</td><td>', $row);
} else {
echo ", " , $row['Dish'];
}
$group = $row['Client'] . '_' . $row['Option']; // update group
}
echo '</td></tr>'; // close final iteration
echo '</table>';
}
I have Two Tables userwhich has field userName and another table page which has field pageUserName so im selecting this two tables form the database in while loop but i want to echo this two Names in same while loop one after another like we have in FB their are userName as Well as Page names in news feed how can i do this ????
<?php
$sql=mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID") ;
while($row=mysql_fetch_assoc());
{
//For First Loop It Should Be UserName
echo $row['userName'];
//For 2nd Loop It Should Be pageUserName
echo $row['pageUserName'];
} ?>
This is the code but the echo gets print together i want separate echo for userName and another for pageUserName one after another and not together
You mean this?
<?php
$sql=mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID") ;
while($row=mysql_fetch_assoc())
{
echo $row['userName'] . ' ' . $row['pageUserName'];
}
?>
inside loop make a single line as follows:
<?php echo $row['userName']. " - ". $row['pageUserName']."<br>" ?>
<?php
$sql=mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID") ;
while($row=mysql_fetch_assoc());
{
echo $row['userName']." ".$row['pageUserName']."<br />";
}
?>
Try like this:
<?php
$sql = mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID");
while ($row = mysql_fetch_assoc()) {
echo $row['userName'] . " " . $row['pageUserName'] . "<br>";
}
?>
NOTE
You should not use open / end php tag in each row.
You can concatenate your string with . character as in my example.
WARNING
mysql_* functions are deprecated, use mysqli_* or PDO instead.
UPDATE
Based on OP edit in his original question, I think I get it what he wants. When you iterate through your results, instead echo put them into 2 arrays.
Then iterate through both of them. I write for this a little function called showNames, so you avoid code repetation.
function showNames($array) {
foreach ($array as $item) {
echo $item."<br>";
}
}
//Init arrays
$userNames = [];
$pageUserNames = [];
while ($row = mysql_fetch_assoc()) {
//Put values into the 2 arrays
$userNames[] = $row['userName'];
$pageUserNames[] = $row['pageUserName'];
}
//Show the items of arrays
showNames($userNames);
echo '<hr>';
showNames($pageUserNames);
I am very new, I am having a small problem.. I cannot get my while loop to loop through my entire result set, it is only retrieving the last result set, and i am expecting 2 result sets.
I echo'd my query out to see the result i would get, and the echo printed out both the result sets i want to print out. Leading me to the confusion my while loop is the issue.
I have looked through lost on here but the posts i have seen it was a problem with their query, rather then their while loop. Any assistance would be greatly appreciated. I have used different posts on here to construct my query, but i don't know where to go from here.
date_default_timezone_set("Europe/London");
$date = jddayofweek(unixtojd());
$sql = "SELECT * FROM tbl WHERE ID = $ID AND Day = $date";
$results = $conn->query($sql);
echo $sql;
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$output = "Test2" . "</br>" . $row["time"] . "</br>";
}
} else {
$output = $output . "test1" . "</br>";
}
}
You are not echoing anything inside your while loop.
I think you need to concatenate the variable $output.
while ($row = $results->fetch_assoc()) {
$output .= "Test2" . "</br>" . $row["time"] . "</br>";
}
You are overwritting the content of $output on every iteration of the loop, you should use the concatenation operator to attach the value of the content to the end of the string.
$output .= "Test2" . "</br>" . $row["time"] . "</br>";
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>';
I am trying to achieve a sorted list with a section separator from a mysql table via php, but am having a bit of trouble. Instead of putting my soup in the soup header like I want, I am putting it in the following header(like I don't want)!
Here is the visual output:
2-Soup
3-Salad
2 Soup Demo: Tom KaKai
4-Entree
3 Salad Demo: Spinach Salad
4 Entree Demo: Pork Chop
4 Entree Demo: Spicy Topped Shrimp
here is my code:
$cat = null;
while($row = mysql_fetch_array($result))
{
if( $row['catnum'] != $cat )
{
echo '<h1>' . $row['catnum'] . '-' . $row['ctgry'] . '</h1>';
$cat = $row['catnum'];
}
echo "<table><tr><td>" . $row['catnum'] . " </td><td>" . $row['ctgry'] . "</td><td> " . $row['Shrt_Desc'] . "</td></tr>";
}
You're not closing your <table> tag and are starting a new table for every DB row retrieved, so structurally your HTML page is a total mess.
You'd want something like this:
$first = true;
while ($row = mysql_fetch_array($result)) {
if ($row['catnum'] != $cat) {
if (!$first) {
echo '</table>'; // close the table if we're NOT the first row being output.
}
$first = false; // no longer the first table, so disable this check.
echo '<h1> etc...';
echo '<table>'; // start new table
$cat = $row['catnum'];
}
echo '<tr><td>' etc.... // output a table row
}
This code will only output the <table> and <h1> stuff when you change categories.