PHP For Loop Count in While Statement - php

I'm trying to figure out the best solution on how to output my html with the php while counting up on a div class.
This is my function that prints news:
function post_news()
{
$post_news = $this->mysql->Query("SELECT * FROM news ORDER BY id DESC LIMIT 4");
while ($news_row = mysqli_fetch_array($post_news))
{
echo "<div class='column1'>
<div class='box'>
<h3>".$news_row['title']."</h3>
<p>".$news_row['content']."</p>
<a href='index.php?p=news&id=".$news_row['id']."' class='button button-small'>Read More</a> </div>
</div>";
}
}
What I am attempting is, where it shows <div class='column1'> I need it to count upward to class='column4'. When I attempt For loops or a second While loop I can sometimes get it to count but it always does a new line where I want these blocks to display side by side like normal.
So what is the best way to count up on my div class without it doing a line break after every block?

I assume that when you say 1 to 4 you want it to start over at 1 after 4. Just increment a counter and reset it when it reaches 4:
$num = 0;
while ($news_row = mysqli_fetch_array($post_news))
{
$num++;
echo "<div class='column{$num}'>
<div class='box'>
<h3>".$news_row['title']."</h3>
<p>".$news_row['content']."</p>
<a href='index.php?p=news&id=".$news_row['id']."' class='button button-small'>Read More</a> </div>
</div>";
if($num == 4) { $num = 0; }
}
Or actually, you use LIMIT 4 in the query so you don't really need the if statement that resets it to 0, as the loop will only iterate 4 times.

A pure html workaround to this would be to have the code like so:
<div class='column1'>
...
</div><div class='column2'>
..
</div>
But because you're echoing it that's not going to work. Another thing you can do is specify an inline-block css property for those columns. If you're using bootstrap you can just use col-xs-3 so that you can have 4 even columns.
If not, instead you're going to have to specify each of those classes to be width:25%
So to wrap up, in css:
.col{
width:25%;/*probably going to have make responsive for screen width*/
display:inline-block;/*or float:left, whichever*/
}
And in php/html:
...
echo "<div class='column1 col'>
<div class='box'>
<h3>".$news_row['title']."</h3>
<p>".$news_row['content']."</p>
<a href='index.php?p=news&id=".$news_row['id']."' class='button button-small'>Read More</a> </div>
</div>";
...
Hope that helps.

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.

every item load with diffrent fancy border

hi guys i am trying to do this like i have 5 frames (fancy border) and i have items list. when items load every item load different frame. when 5 frame done then 6th frame repeat frames list. below my script
<?php
$allgfts=mysql_query("select id,image_url from {$statement} order by id limit {$startpoint}, {$limit}");
while($gfts=mysql_fetch_array($allgfts))
{
$id=$gfts['id'];
$image=$gfts['image_url'];
?>
<div id="pic-1">
<div class="thumbnail-item">
<?php echo '<img src="images/'.$image.'" alt="" width="161" height="161" class="thumbnail g-size" />'; ?>
<span><?php echo 'Readmore';?></span>
<?php echo '<a class="gtbtn" href="g_buy.php?id='.$id.'">Get This</a>';?>
</div>
</div>
<?php
}
?>
I think you're asking how to echo a list of images, with that list wrapping to a new line every fifth item.
Given an array of results from a table (consider using PDO, by the way), I would do the following:
//$arr being the array
$x=1; //start counter
$list = '<ul>'; //using a list, because that's what it is
for($i=0;$i<count($arr);$i++) {
$list.='<li class="thumbnail-item">';
$thumb ='<a href="g_detail.php?id='.$arr[$i][id].'">';
$thumb.='<img src="images/'.$arr[$i][image_url].'" alt="" class="thumbnail g-size" /></a>';
$thumb.='<span><a href="g_detail.php?id='.$arr[$i][id].'>Readmore</a></span>';
$thumb.='<a class="gtbtn" href="g_buy.php?id='.$arr[$i][id].'">Get This</a>';
$list.=$thumb;
$list.='</li>';
if($x%5 == 0)||($x==count($arr)) {
$list.='</ul>';
if($x<count($arr)) {
$list.='<ul>';
}
}
$x++;
}
echo $list;
This is untested, but broadly speaking should work.
Use the remainder operator("%"). I don't know what your table structure looks like, but I am going to assume your product ID loads in sequential order, starting with 1.
In your WHILE loop, use the following:
$remainder = $id % 5;
if($remainder == 1){
//load my DIV with frame 1
}
else($remainder == 2){
//load my DIV with frame 2
}
......

CSS Class on end MySQL row

I am having trouble creating a solution that will target the end row of a MySQL query. Currently I have a foreach function that works through the query and displays each one as a div with the information inside:
<?php $residents = Resident::find_all();
foreach($residents as $resident): ?>
<div class="submenu">
<p class="menuitem submenuheader"><?php echo $resident->name; ?></p>
<img src="images/<?php echo $resident->image_path(); ?>" width="250" class="image" />
<p><?php echo $resident->info; ?></p>
</div>
.submenu currently has a bottom border. I need to remove this on the last row returned. I have looked at DESC LIMIT 1, however this requires another MySQL query and could make things very messy...
Addd this to your CSS:
.submenu:last-child { border-bottom: 0; }
Note: this is not supported by IE < 9.
You could switch to putting the border on the top of the element, and use the :first-child pseudo selector in CSS to remove it.
http://reference.sitepoint.com/css/pseudoclass-firstchild
The :last-child selector would be nice, but it's not supported in IE before version 9, so it's not a good idea to use it if you want compatibility.
If you separate your HTML and PHP a little this is easily achieved:
<?php
function echoBlock($resident,$pClass="menuitem submenuheader") {
echo "<div class=\"submenu\">\n<p class=\"$pClass\">\n";
echo $resident->name;
echo "</p>\n<img src=\"images/";
echo $resident->image_path();
echo "\" width=\"250\" class=\"image\" />\n<p>";
echo $resident->info;
echo "</p>\n</div>\n\n";
}
$residents = Resident::find_all();
$last=count($residents)-1;//2 element array last pos is 1
for ($i=0;$i<$last;$i++) {
echoBlock($residents[$i]);
}
echoBlock($residents[$last],"menuitem");
?>
echoBlock (which could easily be a method on a class) requires the calling code to know about the classes it uses, which isn't really separating intent but it does prevent the need for an if branch on every loop. That being said it would be less efficient but perhaps more usable to set it up as:
function echoBlock($resident,$isLast=false) {
$pClass="menuitem".($isLast?"":" submenuheader");
//...
Which then doesn't need the caller to know anything about what echoBlock does.
You could try and pop the array using array_pop(), to get the last value out of the array and then inputing it using the special class after the foreach loop.
What about
Instead of echo'ing each line one by one, create one big string in PHP, search for the last entry of "submenu" and change the class.

Weird Spaces After PHP Generated HTML

I have a weird issue. I have a dynamic website www.lamanscanada.com it appears fine in firefox and safari and almost perfect in IE7. But it appears that on certain php generated html. There is a bunch of space added after the function output. I also user mod_rewrite for nice SEO urls just a note.
The function sorts an array of data into columns with bullets
<?php
//breaks array values into two columns
function groupBullets($array){
//count the array items
$bulletcount = count($array);
//divides that in two and round the result
$roundhalf = round(($bulletcount/2));
//initailize a counting variable
$i=1;
//loop throught the array
foreach($array as $bullet){
//if it is the first item
if($i==1){
echo "<span class=\"container\">";//open the main container div
}
echo "<span class=\"bullet\">• $bullet</span>";//then create bullet
//if the counter is at the half mark
if($i==$roundhalf){
echo "</span>";//close the container
$i=1;//and start the counter over
}else{
$i++;//if not at half keep counting
}
}
}
//end
//I am implementing it like this:
//this is my array it actually has a second level
$array = array(
columngroup01("bullet 1","bullet 2","bullet 3","bullet 4"),
columngroup02("bullet 1","bullet 2","bullet 3","bullet 4")
);
//I loop through this array
foreach($array as $column=>$arrayofbullets){
echo "<div class=\"columncontainer\">".//open the div contains the columns
"<div class=\"heading\">$column</div>";//print the title of the column
//use the groupBullets function on each array of bullets
groupBullets($arrayofbullets);
echo "</div>";//close the column container
}
?>
The <span class="features"> is not being closed at the end of the generated list of <span class="featureitem"> tags.
Current generated output:
<div class="infoblock">
<div class="infoheading">features</div>
<span class="features">
<span class="featureitem">• 10'X6'X8' Aluminum Extrusion Structure</span>
<span class="featureitem">• R18 Insulated Panels</span>
...
</div>
Needs to be:
<div class="infoblock">
<div class="infoheading">features</div>
<span class="features">
<span class="featureitem">• 10'X6'X8' Aluminum Extrusion Structure</span>
<span class="featureitem">• R18 Insulated Panels</span>
...
</span>
</div>

PHP/MySQL 2 'while' statements from 1 mysql query?

I was wondering if it's possible to have 2 'while' statements using the same 'mysql_query'?
I'm using a jquery thumb gallery with the results pulled in from a database. The gallery requires that the images are grouped together in an unordered list, with the text/overlayed content grouped together in hidden divs which need to be separate from the unordered list. The reason for doing this is because there are many potential results that could go in here and bringing them in randomly seems to make sense.
Here's the code I'm currently using: Any help greatly appreciated, S.
<div id="banner-wrap">
<div id="banner" class="gallery">
<ul class="galleryBar">
<?php
$homeB=mysql_query("select * from istable where fpGallery = '1' ORDER BY RAND() LIMIT 0, 5");
while($homeG=mysql_fetch_array($homeB)) {
$linkcode = $homeG['title'];
$linkcode = str_replace(" ","",$linkcode);
echo '
<li>
<a href="'.$wwwUrl.'images/'.$homeG['image'].'" rel="'.$linkcode.'">
<img src="'.$wwwUrl.'images/tn/'.$homeG['image'].'" width="75" height="55" alt="'.$homeG['title'].'" />
</a>
</li>
';
}
echo '</ul>';
echo '</div>';
while($homeGal=mysql_fetch_array($homeB)) {
echo '
<div id="'.$linkcode.'" class="overlay">
<h3>'.$homeGal['title'].'</h3>
<h4>'.$homeGal['location'].'</h4>
</div>
';
}
?>
</div>
Try to reset the iterator of the query result by calling mysql_data_seek($homeB, 0) between the two while loops.
WHERE `column1` = 'value1' AND `column2` = 'value2'
Your unindented code is hard to follow but it appears that you're asking whether mysql_fetch_array() starts again when it reaches the last row. The answer to that is no.
Can you rewind the result set? In theory, you can (find mysql_data_seek() in the manual). But there's no need to make it so complicate: just read data once, store it into an array and loop the array as many times as you need.

Categories