Group by first letter, alphabetically, best way? - php

Here is my code:
<div class="widgeter-content no-padding">
<ul id="contacts">
<?php
while ($r = mysql_fetch_array($q)){
$currentletter = substr($name,0,1);
if ($currentletter != $lastletter){
?>
<!-- start li data group for specific alphabetic letter -->
<li data-group="<?=$currentletter;?>">
<a class="title"><?=strtoupper($currentletter);?></a>
<?
}
?>
<ul>
<li>
<a href="#">
<span><?=$name;?></span>
</a>
</li>
</ul>
<?
if ($currentletter != $lastletter){
?>
</li>
<!-- end data group (not currently working, ends on first result) -->
<?
}
$lastletter = $currentletter;
}
?>
</ul>
</div>
What I am trying to do:
A:
Alfred
Annie
B:
Bob
Billy
As you can see, the data is wrapped in an li data group.
The first part of the code works perfectly, but the last part (where I'm trying to put the closing li tag before the end comment, shows after the first result of each loop, where it needs to show at the END of each letters results).
What would be the best way to do this? I'm sure its quite obvious what I'm trying to achieve but I can't think of a logical way to get the code structuring how I want it to.
Thank you

$res = array();
while ($r = mysql_fetch_array($q)){
$currentletter = substr($name,0,1);
$res[$currentletter][] = $name;
}
foreach($res as $key=>$val){
/// here you add your li
/// here $key will give you letter and $val will give you name
echo $key;
foreach($val as $reqvals){
echo $reqvals;
echo "<br>";
}
}

What would be the best way to do this?
If you are fetching row from the database why can not rather GROUP BY there and get the records. That's the preferred way of doing it.
Assuming that the column name is first_name
group by substr(first_name,1,1)

Related

Access a special div, generated by a while loop

I'll try to be clear. My problem is that i'm using php to get data from mysql. The table has more than one record. To show table records i'm using a while loop that as a condition has mysqli_fetch_array(). The records from the table must be shown in an echo(because i want to show them as html on the page), but every div generated from the while loop has a link to send me to another page, and if the client clicks on that link it will get the current divs information(after the table in database has more than one record the informations will be different) to be shown at the next page. Hope you understood it. Thanks in advance!
while($rows1 = mysqli_fetch_array($query1,MYSQLI_ASSOC))
{
echo "<div class=\"row\">
<div class=\"col-md-6\">
<div class=\"thumb\">
<figure>
<img src=\"images/extra-images/room-grid1.jpg\" alt=\"\"/>
<figcaption>
<a rel=\"prettyPhoto[gallery2]\" href=\"images/extra-images/room-grid1.jpg\">
<i class=\"fa fa-search\"></i>
</a>
</figcaption>
</figure>
</div>
</div>
<div class=\"col-md-6\">
<div class=\"text\">
<h4>".$rows1['Dh_lloji']."</h4>
<p>".$rows1['Dh_Pershkrimi']."</p>
<ul class=\"room-grid-meta\">
<li>Max: ".$rows1['Dh_Kapaciteti']."</li>
<li>Size: ".$rows1['Dh_madhesia']."</li>
<li>Floor: ".$rows1['Dh_Kati']."</li>
</ul>
<div class=\"retail room-grid-retail\">
<span>
<sup>$</sup>
".$rows1['Dh_cmimi']."
<sub>night</sub>
</span>";
if(isset($_SESSION['Emri_Mbiemri']) != '')
{
echo "<a class=\"btn-3\" href=\"payment.php\">Book now</a>";
}else{
$error = "You must be logged in to book!";
}
echo "<br>".$error."</div>
<div id=\"price_room\">".$rows1['Dh_cmimi']."</div>
</div>
</div>
</div>";
$count++;
}
Looks like you need at least your custom counter, that will be increment inside cycle, and set div's id based on this counter plus use it in generated link
I made a solution for my problem and i wanted to share it with you guys. I gave a $count to the links defining every link the while loop generates...
<a class=\"btn-3\" href=\"payment.php?id=$count\">Book now</a>
After that i used a multidimensional array to store the current divs variable(in my case rooms price, the count, and the id) of the room from database...
$room_prices[$count][0] = $rows1['Dh_cmimi'];
$room_prices[$count][1] = $count;
$room_prices[$count][2] = $rows1['ID_Dhoma'];
After the client click a specific link he will get the id so i can make a search at my multidimensional array for the price and the id of that room..
for($i = 0; $i < $count; $i++)
{
if($_GET['id'] == $room_prices[$i][1]){
$sess_room_price = $room_prices[$i][0];
$sess_room_id = $room_prices[$i][2];
}
}
After i get these i store them at the global session variables to use them at the other page...
$_SESSION['Rooms_Price'] = $sess_room_price;
$_SESSION['Rooms_ID'] = $sess_room_id;
So this did the work for me... Hope this helps others.

How to add an item containing sub-items in each iteration of a loop?

Sorry if this seems very simple I'm rather new to php.
I'm drawing data from the database using a for each loop and want to add a list item for each result to a side bar while adding a new container div to the body.
What is the best way to code this?
Any help is much appreciated.
Thanks A
Edit...
My code so far...
<?php
$iidcoversheets = $wpdb->get_results(
"
SELECT *
FROM $wpdb->trm_iid_cover_sheet
WHERE Return_ID_FK = '$trmrtnid->Return_ID_PK'
"
);
$gadcoversheets = $wpdb->get_results(
"
SELECT *
FROM $wpdb->trm_gad_cover_sheet
WHERE Return_ID_FK = '$trmrtnid->Return_ID_PK'
"
);
?>
<ul>
<?php
foreach ( $iidcoversheets as $iidcoversheet )
{
?>
<li><?php echo $iidcoversheet->business name; ?></li>
<?php
}
?>
<?php
foreach ( $gadcoversheets as $gadcoversheet )
{
?>
<li><?php echo $gadcoversheet->business name; ?></li>
<?php
}
?>
</ul>
I understand how to add the <li> items but I'm strugging on how to add a div containing some html to another div not in the <ul> tag as it seems to me this will interrupt the code for the <ul>.
Any help would be really appreciated.
Thanks A
<div>
<ol>
<?php
foreach ($uls as $ul) {
?>
<li>
<?php echo $ul; ?>
</li>
<?php
}
?>
</ol>
</div>
Ok I came to the realisation that I could simply do another exact same loop later on in the page in the div I wanted but with different output. I was trying to do it all up front save the results and output them somewhere else, unnecessary.
Clearly I was having a daft moment earlier.
Thanks for all the input.
Regards
A

PHP MySQL Order list

Can anyone help?
My code is like this:
<ol><li>{$student_Value}</li> <ol>'
it gives result:
1. Student101Name
1. Student102Name
1. Student103Name
I want something like:
Student101Name
Student102Name
Student103Name
Please help... Thank you!
Do not close the OL tag every time
OL = Ordered List
LI = List item
If you close and reopen the OL, it creates a new ordered list, and so restarting at 1.
<pre>
echo "<ol>";
foreach loop {
echo "<li>{$student_Value}</li>";
}
echo "</ol>";
</pre>
Good luck.
If you use MySQL to get the data you can add ORDER BY to the query to order the result!
Here more info how to use ORDER BY
And change the HTML Code to be:
<ol>
<li>$student_Value</li>
<li>$student_Value</li>
<li>$student_Value</li>
</ol>
PHP Code will be:
echo "<ol>";
echo " <li> $student_Value </li> ";//write all student values like this
//more student values
echo "</ol>";
It looks like your problem is more CSS related than PHP or SQL.
The reason is probably that your output is:
<ol><li>$student_Value</li></ol>
<ol><li>$student_Value</li></ol>
<ol><li>$student_Value</li></ol>
Each student should be a list item within the ordered list:
<?php
print "<ol>";
while ($row = $result->fetch_assoc())
{
print "<li>{$row['student']}</li>";
}
print "</ol>";
?>
You need something like that
<ol>
<?php
for($i=0; $i<count($studentValue); $i++)
{
?>
<li><?php echo $studentValue[$i]; ?></li>
<?php
}
?>
<ol>
I am giving you above example to tell you that under a 'ol' tag 'li' must be multiple to get your require result.

Making A List Using PHP And NestedSortable

I'm attempting to make my own CMS and one thing I wanted to do was make it so I could reorder and change the navigation elements in the CMS. I found a plugin called NestedSortable that let me do this. I used it and had a lot of trouble with it, so I got my expert PHP friend to help me do it. She sat down, struggled for a bit and then got it to work.
Well, the idiot I was, when I got home later that day I sat down, took my local copy, added a something to it and uploaded it to the server... not realizing I had forgotten to download the newer version! So poof, all my friend's work is gone and I'm stuck with a navigation adjustment that doesn't work.
I lost the index.php (that displays it on the page) file but I saved the nav_adjust.php (that inputs it into the database). All I want is to be able to re-order the navigation and send it to the database to be displayed correctly on refresh. The information is send to nav_adjust.php when the submit button is pressed.
The only limitation is that the navigation can only have 3 levels to it (primary, child and grandchild). My navigation looks like when they're all primary. I have alerted back the echo for all the images so you can see what nav_adust.php is doing:
(Please note the array values.)
This is as if there was one child on a parent:
This is as if there was two grandchildren on a child:
And this is mixed:
My index.php file, which doesn't work anymore, looks like this:
<form method="post" action="nav_adjust.php"> <!--This form posts to nav_adjust.php-->
<ol id="pageList">
<?php
$nav = mysql_query("SELECT * FROM `".$name['Website']);
$num = 0;
while( $col_nav = mysql_fetch_assoc($nav) ){
if ($col_nav['orderId'] != 0) {
echo "<li id='list_".$col_nav['id']."'>
<div>Example Title</div>";
} else {
echo "<ol>
<li id='list_".$col_nav['id']."'>
<div><h1>Example Title</div>";
</li>
</ol>\n";
}
echo "</li>\n";
++$num;
}
?>
</ol>
<button type='submit'>Update</button>
</form>
<script>
$(document).ready(function(){
$('#pageList').nestedSortable({
/*option that don't matter*/
});
$("button").on('click', function(event){
serialized = $('ol#pageList').nestedSortable('serialize');
$.post( "nav_adjust.php", serialized, function( data ) {
alert( data );
});
return false;
});
});
</script>
Again, the above code doesn't work. Instead of making a list item look like this:
<ol>
<li>
<ol>
<li></li>
...
</ol>
</li>
...
</ol>
It makes it look like this (note the closed li tag before the ol):
<ol>
<li></li>
<ol>
<li></li>
</ol>
...
</ol>
And this is the nav_adjust.php that my friend did for me which works beautifully if given the right information from index.php
$list = $_POST['list'];
$num = 1;
foreach ($list as $key => $value ) {
if ($value == "null") {
//$value = $num;
mysql_query("UPDATE `myTable` SET orderId=".$num.", parent='null' WHERE id=".$key."");
$text .= "UPDATE `myTable` SET orderId=".$num.", parent='null' WHERE id=".$key."\n\n";
} else {
$query = "UPDATE `myTable` SET orderId=". $num .", parent=".$value;
$text .= "UPDATE `myTable` SET orderId=". $num .", parent=".$value."\n\n";
$var = $list[$value];
if ( $var != null && $list[$var] != null ) {
$query .= ", grandchild = 1";
}
$query .= " WHERE id=".$key;
mysql_query($query);
}
$num++;
}
echo "Content is below\n";
print_r( $_POST['list']);
echo $text;
So, as a recap, I have a navigation that submits serialized data from index.php to nav_adjust.php which then submits it into a database (and echos it back so I know what I did). Then index.php, upon refresh, should keep the list items in place, with all children as children and such. But I overwrite index.php and have no idea how my friend did it.
My table fields are (before I forget):
id, title, orderId (parent), parent (child) and grandchild.
I was meaning to change the names of orderId and parent to make it less confusing but I never did :(
If somebody could help me, I'd be so very thankful.
If there is any other information I can give you, please ask!
After hours of struggling, I had the genius idea of asking GoDaddy if they backed up files and directories, and they did! So I got my file back. For anybody interested, the code missing on index.php looked like this (where $name['website'] is 'myTable'):
$parents = mysql_query("SELECT * FROM `".$name['Website']."` WHERE parent = 0 ORDER BY `orderId` ASC");
while($parent = mysql_fetch_array($parents)){
echo "<li id='list_".$parent['id']."'>
<div>
<span class='disclose'>
<span></span>
</span>
<span class='title'>
<a href='mod.php?id=".$parent['id']."'>".stripslashes($parent['page'])."</a>
</span>
</div>";
// Get chil elements
$children = mysql_query("SELECT * FROM `".$name['Website']."` WHERE parent = " . $parent['id'] . " ORDER BY `orderId` ASC") or die(mysql_error());
while($child = mysql_fetch_array($children)){
echo "<ol>
<li id='list_".$child['id']."'>
<div>
<span class='disclose'>
<span></span>
</span>
<span class='title'>
<a href='mod.php?id=".$child['id']."'>".stripslashes($child['page'])."</a>
</span>
</div>";
# Get grandchild elements
# (Please consider making an recursive function or so out of this if you plan to have grand grand children etc.,
# Because if you create new whiles manually for every instance, this is gonna look pretty darn ugly.
# Also, it makes it impossible to have an unknown depth.)
$grandchildren = mysql_query("SELECT * FROM `".$name['Website']."` WHERE parent = " . $child['id'] . " AND grandchild = 1 ORDER BY `orderId` ASC");
while($grandchild = mysql_fetch_array($grandchildren)){
echo "<ol>
<li id='list_".$grandchild['id']."'>
<div>
<span class='disclose'>
<span></span>
</span>
<span class='title'>
<a href='mod.php?id=".$grandchild['id']."'>".stripslashes($grandchild['page'])."</a>
</span>
</div>
</li>
</ol>\n";
}
// Close child
echo "</li>
</ol>\n";
}
// Close parent
echo "</li>\n";
}
?>

displaying records from mysql in ul and li format with php

i want to display the mysql's fetched results with php and html in unordered list and list format as like http://www.miniclip.com/games/en/. you can see in the all games categories in the footer in alphabetical order. the same requirement i do have. i guess i have written the logic its working fine. but i am unable to represent it properly. you can see in the following link above the footer. http://www.playtoongames.com/play1...
code:
<?php
$gameQuery = mysql_query ("SELECT name, LEFT(name, 1) AS first_char FROM games WHERE UPPER(name) BETWEEN 'A' AND 'Z' OR name BETWEEN '0' AND '9' ORDER BY name");
$current_char = '';
while ($gameRow = mysql_fetch_assoc($gameQuery)){
if ($_SESSION['lang'] == 'fr'){
$description = $gameRow['description_fr'];
}else{
$description = $gameRow['description'];
}
?>
<div style='float:left' title="<img src='<?php echo $gameRow['sitePath'];?>games/images/<?php echo $gameRow['img_100x75'];?>' width='230' height='112' class='thumb' alt='<?php echo $gameRow['name'];?>'/>" class='tooltip'>
<ul>
<li>
<a href='<?php echo $gameRow['sitePath'];?>play/<?php echo str_replace(' ','_',$gameRow['name']);?>'><?php echo $gameRow['name'];?></a>
</li>
</ul>
</div>
can anybody look into this...
Regards,
sam.
On the Playtoons site, each <li> is in its' own individual <ul> - this means you're creating a new list for each item:
<ul>
<li>13 More Days</li>
</ul>
<ul>
<li>A Bikers Heaven</li>
</ul>
What you should be doing is using one <ul> which contains all the items as <li>s:
<ul>
<li>13 More Days</li>
<li>A Bikers Heaven</li>
</ul>
Well, I think the key is that there are 6 columns, which just means you'll need to break your array into 6 different parts.
Here's some psuedocode:
$pArr = $from_sql_array; // I'll let you take care of that.
$itmCount = count($pArr);
$itmsPerCol = ceil($itmCount / 6.0);
for ($ii=0; $ii < 6; $ii++)
{
$pCol = array_slice($pArr, $itmsPerCol * $ii, $itmsPerCol);
echo '<ul class="floatleft"><li>'.implode("</li>\n<li>",$pCol).'</li></ul>';
}

Categories