I have a mysql table with 3 fields: id, client, group and some data.
I need to display the results in groups, on a css table, like this:
group A
- John
- Paul
- Ringo
- George
group B
- Mick
- Keith
- Charlie
group C
- Axl
- Slash
- Izzy
I have to put a while inside another while? I really don't get the logic behing this conditional... Can someone help me?
I have this so far:
while($row = mysql_fetch_array($result) ){
echo "<div>".$row['group']."</div>";
while($currentGroup != $group ){
echo "<div><B>".$row['id']."</b></div>";
echo "<div>".$row['client']."</div>";
}
$currentGroup = $group;
}
Thanks!
Like this:
$currentGroup = false;
while ($row = mysql_fetch_array($result))
{
if ($row['group'] !== $currentGroup)
{
echo "<div>".$row['group']."</div>";
$currentGroup = $row['group'];
}
echo "<div><B>".$row['id']."</b></div>";
echo "<div>".$row['client']."</div>";
}
Related
In my code i get a bunch of results from my database like so:
$records = $conn->prepare('SELECT sm.taak,u.username FROM schedule_mon AS sm JOIN users AS u ON sm.user_id=u.id');
$records->execute();
$results = $records -> fetchAll();
Then i loop through the results like this:
foreach( $results as $row ) {
echo $row['taak']." ".$row['username']."</br>";
}
My results look like this:
Tafel dekken Peter
Tafel afruimen Chrisformer
Afwasmachine inruimen Frek
Afwasmachine uitruimen desley
The format is basically a task and then the user that has to perform that task. I would now like to know, lets say the user that has to perform a task is named Peter. How do i give peter a different color than the others.
So if user = peter then put peter in an <li> with a certain class. So i can give it a distinct color in css.
Use a <span> around the part you want to color differently:
foreach( $results as $row ) {
if ($row['username'] == "Peter") {
echo $row['taak']." <span class='className'>".$row['username']."</span></br>";
} else {
echo $row['taak']." ".$row['username']."</br>";
}
}
Than use CSS to assign a color to the className:
.className {
color:red;
}
With the following code:
//turn items into an array
$item_array = array('abc','xyz2','Good','nice-b');
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product_items = array();
$productList = array();
$result = $mysqli->query("SELECT Name, WebsitePrice as price, WebsiteStock as stock from table_products where Name IN ('$item_implode')");
if ($result->num_rows > 0) {
$x = 1;
// output data of each row
while($row = $result->fetch_assoc()) {
$product_items[$x]["Name"] = $row['Name'];
$product_items[$x]["price"] = $row['price'];
$product_items[$x]["stock"] = $row['stock'];
$x = $x + 1;
}
} else {
echo "0 results";
}
I'm getting this output:
abc- 99 - yes
xyz - 20 - yes
Good - 30 - yes
nice-b - 55 - yes
But when I use an item called Hello1 instead of Good, like this:
$item_array = array('abc','xyz2','Hello1','nice-b');
I'm getting this output:
abc- 99 - yes
Hello1 - 77 - yes
xyz - 20 - yes
nice-b - 55 - yes
Meaning that the name of the object is causing some change in the order of the array, and it becomes the second item, even though it should be the third one.
What's causing this?
Use ORDER BY FIELD(Name, 'abc','xyz2','Good','nice-b'); in your query. You could use $item_implode for reusability.
[Fetched from comments]
In the SQL world, order is not an inherent property of a set of data. Thus, you get no guarantees from your RDBMS that your data will come back in a certain order -- or even in a consistent order -- unless you query your data with an ORDER BY clause.
There is no guarantee that MySQL will return the results in the order you set the IDs in the IN clause.
Later edit: Based on your last comment you can do something like this:
if ($result->num_rows > 0) {
$product_items = array_flip($item_array);
// output data of each row
while($row = $result->fetch_assoc()) {
$product_items[$row['Name']] = array();
$product_items[$row['Name']]["Name"] = $row['Name'];
$product_items[$row['Name']]["price"] = $row['price'];
$product_items[$row['Name']]["stock"] = $row['stock'];
}
}
I have a MySQL query that returns a number of records. For example:
+-------+------------+-----------+
| group | first_name | last_name |
+-------+------------+-----------+
| Red | John | Doe |
+-------+------------+-----------+
| Red | Jane | Doe |
+-------+------------+-----------+
| Green | Bob | Anybody |
+-------+------------+-----------+
| Black | Betty | Anybody |
+-------+------------+-----------+
I also have defined several group names in a PHP array:
$importantGroups = array('Red', 'Blue', 'Green');
Using the query results, I'm trying to write a PHP script that will create an unordered HTML list for each group that's defined in the array.
If a group doesn't appear in any query results, then that list doesn't get created.
If a result has group value that doesn't appear in the array, it's placed in a ul at the end.
Using the query results above, the HTML output would be:
<ul id="Red">
<li>John Doe</li>
<li>Jane Doe</li>
</ul>
<ul id="Green">
<li>Bob Anybody</li>
</ul>
<ul id="Other">
<li>Betty Anybody</li>
</ul>
Any help on the best way to make this work?
First, do the ordering in SQL like this:
SELECT ... ORDER BY FIELD(`group`, 'Green', 'Blue', 'Red') DESC
The parameters for FIELD should be in reverse order of their importance, results not in this group will be sorted to the end.
During output, just break into a new group whenever you encounter one:
$group = null;
while ($row = /* get result */) {
if (!in_array($row['group'], $importantGroups)) {
$row['group'] = 'other';
}
if ($row['group'] != $group) {
if ($group !== null) {
echo '</ul>';
}
printf('<ul id="%s">', $row['group']);
$group = $row['group'];
}
printf('<li>%s</li>', $row['name']);
}
if ($group !== null) {
echo '</ul>';
}
This is the most efficient way for large result sets. If the sets aren't that large, it's a lot more readable to group them together in PHP and output the groups, as demonstrated in the other answers.
This is a little janky, I think there may be some way to add efficiency but it certainly works.
<?php
$importantGroups = array('Red', 'Blue', 'Green');
$sql = "SELECT * FROM `table`";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
if(array_search($row['group'],$importantGroups)){
$groupName = $row['group'];
}else{
$groupName = "Other";
}
$groups[ $groupName ][] = $row;
}
$importantGroups[] = "Other";
foreach($importantGroups as $groupName){
echo '<ul id="' . $groupName . '">';
foreach($groups[$groupName] as $element){
echo '<li>' . $element['first_name'] . ' ' . $element['last_name'] . '</li>';
}
echo '</ul>';
}
?>
This is a really basic script, and you should really look into finding out more about how PHP and mySQL work together instead of just asking for help. I'll post the basic flow to help you in the correct order of operations and the resources to help you along. To start I'd recommend reading this how-to on Tizag, which should help you fully understand how these languages work together.
Query SQL to get the data you need
//Connect to the database
//Query for the data
$sql = "SELECT group, first_name, last_name FROM ... WHERE ..."
$results = mysql_query($sql);
Parse the SQL results to create a multi-dimensional array of results
while($result = mysql_fetch_assoc($results){
$array_of_groups[$result["group"]][] = $result;
}
Iterate through the results array to create the desired output
foreach($array_of_groups as $group_name => $group){
//We are now looping groups
echo("<ul id='$group_name'>");
foreach($group as $item){
$item_name = $item["first_name"] . " " . $item["last_name"];
echo("<li>$item_name</li>");
}
echo("</ul>");
}
The above code is untested and really just a stub of what you need. You'll need a test above to figure out what groups are not needed. I'm really going to recommend reading up on that Tizag article and patching up that example code to make sure you understand how it works going forward.
I think it might be better to have three while loops. SELECT * FROM Table WHERE 'Group'='Red', then SELECT * FROM Table WHERE 'Group'='Green', then SELECT * FROM Table WHERE 'Group' NOT IN ('Red','Green'). With each result, put them in UL tags.
For example:
<?php
echo '<ul>';
while($row = mysql_fetch_array($result_Red))
{
echo "<li>" . $row['first_name'] . " " . $row['last_name'] . "</li>";
}
echo "</ul>";
mysql_close($con);
?>
And then again for Green and Other. It might save more time than saving each value to an array, then running a foreach loop to call them. Maybe not. Try it and find out.
I'm trying to get a value to be inserted into a table on a webpage if the value equals $i.
$i starts at a number and decreases every loop. i can get it to work but it outputs multiple lines for each $i equivalent to the results in the table
I've reworked the code using everyones feedback to get this.
Echo "<tr><th colspan='3'><center>$rackname</th> </tr>" ;
for ($i=$RUtotal; $i > 0; $i--)
{
echo" <tr class='rackbg'><td class='i'><center>$i</td>" ;
$sql1 = "SELECT racks.rackID, racks.rackname, devices.deviceID, devices.deviceName, racks.rackRU, devices.deviceRU, devices.RUcount
FROM racks LEFT JOIN devices ON racks.rackID = devices.rackID
WHERE devices.rackID = '$rackID'";
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_assoc($query1))
{
$deviceru = $row['deviceRU'];
$deviceID = $row['deviceID'];
$device = $row['deviceName'];
$deviceRUC = $row['RUcount'];
if ($deviceru == $i)
{
echo '<td class="device" rowspan='.$deviceRUC.'><a onclick=window.location="/devices.php?id='.$deviceID.'">'.$device.'</a></td><td rowspan='.$deviceRUC.'></td></tr>';
}
else
{
;
}
}
}
Echo "<tr class='rackb'><th colspan='3'>a</th></tr> " ;
This works to a degree (picture1) but when i add echo "" to the else statement it displays all wrong. (picture 2)
Any help would be greatly appreciated
Picture1 - http://imageshack.us/photo/my-images/263/examplewq.png/
Picture2 - http://imageshack.us/photo/my-images/269/example2jp.png/
I can't quite see what you're trying to do but what it looks like to me is that you want all the items from racks joined with their relevant device and displayed in order of deviceRU. Does this help:
echo "<tr><th colspan='3'><center><b>$rackname</th></tr>" ;
$sql1 = "SELECT racks.rackID, racks.rackname, devices.deviceID, devices.deviceName, racks.rackRU, devices.deviceRU, devices.RUcount
FROM racks LEFT JOIN devices ON racks.rackID = devices.rackID
WHERE racks.rackID = '$rackID' AND devices.deviceRU <= ".intval($RUtotal)."
ORDER BY devices.deviceRU;"
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1))
{
$deviceru = $row['deviceRU'];
$deviceID = $row['deviceID'];
$device = $row['deviceName'];
$deviceRUC = $row['RUcount'];
echo'<tr class="rackbg"><td class="i">'.$i.'</td><td class="device">'.$device.'</td><td></td></tr>';
}
I've used a LEFT (inner) JOIN in the SQL instead of the outer join that was there before as it'll return less results and might solve your problem. I've ordered the results by deviceRU and only returned results which have deviceRU less than or equal to $RUtotal (as I think the example was showing).
I've also removed the tags, these should be replaced by using CSS to centre either all td elements or centering class="device" and class="i" e.g.:
.device, .i {
text-align: center;
}
I've also swapped your abc to abc which is the correct format for a link.
Could you describe more of the context as it's difficult to see your intention from your post.
Mat
As Peetz said, you don't need nested loop. You need something like:
$i = $RUtotal;
// ...
while ($row = mysql_fetch_array($query1)) {
// ...
if ($deviceru == $i) {
// ...
} else {
// ...
}
// ...
$i--;
}
This is looping $i times, within the outer while loop. This means you are getting the table repeated over and over again.
I suggest you remove the outer while loop.
This is my cats in mysql
cats_id cats_position cats_parentid
1 1> 0
2 1>2> 1
3 3> 0
4 1>2>4> 2
and i am trying to create a navigation like:
index > cars > fiat > punto
from
cat=4&parent=2&position=1>2>4>
I end up getting:
Index carcarcarcar
and my php knowledge is not enough to finish this code. can you help me please.
<?php
$position = trim($_GET['position']);
$pieces = explode(">", $position);
$i=0;
foreach($pieces as $piece){
$result = mysql_query("SELECT * FROM cats
WHERE cats_id='".$pieces[$i]."'");
while($row = mysql_fetch_array($result))
{
$piecesid[$i] = $row['cats_id'];
$piecesname[$i] = $row['cats_name'];
$piecesposition[$i] = $row['cats_position'];
}
$i++;
}
?>
Index
<?php $i=0; foreach($pieces as $piece){
if($i=0)
$parent=0;
else
$parent=$placesid[$i-1];
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent.'&position='.$piecesposition[$i].'">'.$piecesname[$i];
}
Your first error is a missing semicolon here:
$i++;
The second bug is a missing dot after $parent in the echo line:
'&parent='.$parent.'&position='
The third (unexpected end) error will become apparent when you started to indent your code correctly. It's also bad style to omit the curly braces, because that makes it more difficult to find precisely such errors.
And lastly: when posting on Stackoverflow, include the full error message (which always mentions the line number!)
I believe this is what he is looking for:
Create a mysql table with id, parent_id, and name fields.
When a category is a "child" of another, that others parent_id field should be set accordingly, I see you already have something to that effect.
Use this code, setting $cat via $_GET['cat'] or something.
<?php
$cat = mysql_real_escape_string($_GET['cat']);
$res = mysql_query("select id,name,parent_id from categories where id = '$cat'");
$breadcrumb = array();
while ($category = mysql_fetch_object($res) {
$breadcrumb[] = "" . $category->name . "";
if ($category->parent_id != 0) {
$res = mysql_query("select id,name,parent_id from categories where id = '{$category->parent_id}'");
}
}
echo join(" > ", array_reverse($breadcrumb));
?>
You have not closed your foreach in the last php section
<?php $i=0; foreach($pieces as $piece){
if($i=0)
$parent=0;
else
$parent=$placesid[$i-1];
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent'&position='.$piecesposition[$i].'>'.$piecesname[$i];
//Missing } here
?>
you're missing a } at the end. Just put a } after the last line like this:
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent'&position='.$piecesposition[$i].'>'.$piecesname[$i];
}
By the way, you don't need cats_position in your table.
To handle hierarchical data like this you can use a nested set (http://en.wikipedia.org/wiki/Nested_set_model) or just rely on the parent_id.
The advantage of this is, that you for example don't need multiple parameters in your get query. Instead of
cat=4&parent=2&position=1>2>4>
you then archieve the same with:
cat=4