php every sixth row add class - php

I have a mysql query which selects 18 items from the table, but I'd like it to add a class on every 6th item.
Here's my code:
$i = 0;
foreach ($this->Items as $item) {
if ($item->image) {
echo '<div class="storeImages"> <img src="/images/store/'.$item->image.'" width="113" height="153" border="0" alt="'.$item->name.'" title="'.$item->name.'" /> </div>';
};
$i++;
};
I've tried a couple of different things, but can't seem to get it working, basically on each 6th item, I want to add style="margin-right: 0px;" :)

if($i % 6 == 0){
//add class
}
Take a look at the arithmetic operators in the manual.

Have a look at the Mod function (%)
somthing like.
if($i % 6 == 0)
edit: beaten to it.

$style = '';
if ($i % 6 == 0) {
$style = ' style="margin-right: 0px;"';
}
echo '<div class="storeImages" ' . $style . '> <img src="/images/store/'.$item->image.'" width="113" height="153" border="0" alt="'.$item->name.'" title="'.$item->name.'" /> </div>';

Modulo is your friend.

Related

How to make an php loop into an another php loop according to an array?

I am trying to nest a php loop into another php loop according to an php array. First loop will continue the loop according how many elements the array has and I want the second loop will continue according to the element. If the first element is 2 the user input repeat 2 times after that the second element is 3 the user input repeat 3 times. when all the elements are gone the loop stopped. but I don't know how to do it.
<body style="margin: 0 auto; width: 50%;">
<div class="input-field col s12">
<?php
$dolils = array("2","3","4");
$total_dolils = count($dolils);
for ($x = 1; $x <= $total_dolils; $x++) {
?>
<p class="blue-text" style="color: blue; font-weight: bold;"><?php echo $x; ?> নং দিনে দলিলের হিসাবঃ </p>
<?php
$z = 0;
for($y = 0; $y <= $dolils[$z]; $y++) {
?>
<p class="red-text" style="color: red; font-weight: bold;">দলিলের নাম্বার</p>
<input id="input_number" type="number" name="dolils_no[]" data-length="10">
<p>মোট পৃষ্ঠাঃ </p>
<input id="input_number" type="number" name="page[]" data-length="10">
<p>মোট লাইনঃ </p>
<input id="input_number" type="number" name="line[]" data-length="10">
<?php
$z++;
echo "<br/>";
echo $z;
echo "<br/>";
if($z >= end($dolils)){
die;
}
}
}
?>
</div>
</body>
Basic logic:
<?php
$content = '<div>';
$dolils = array (2, 3, 4);
foreach ($dolils as $dolil) {
for ($i = 1; $i <= $dolil; $i++) {
$content .= "<p>iteration {$dolil}/{$i} </p>";
}
}
$content .= '</div>';
// after all
echo $content;
bonus tip:
Stop mixing PHP and HTML like this is not comfortable, error pron and just ugly. Instead build HTML in one piece of PHP code or better get familiar with templating engines and/or MVC patterns.

How to apply if-else on css class in php code?

I am trying to apply if else condition in bootstrap class with php variable but its not working. My variable is getting result.
Below is my tbody where i am applying php code:
<div class="<?php '#count_rows#' <= '2')
{
echo 'middle_menu';
}
else
{
echo 'middle_menu1';
} ?>">
<table class="table_4">
<thead>
<tr>
<th class="th_11">Quantity</th>
</tr>
</thead>
<tbody>
#TABLE_BODY#
</tbody>
</table>
</div>
Below is my 2 css classes:
.middle_menu
{
margin-top: 40px;
padding-bottom: 200px;
}
.middle_menu1
{
margin-top: 40px;
}
I am fetching my variable from another page where i set this type of opening and closing variable with #.
Below is my code for your reference but i dont think that is an issue for me because i check this #count_rows# variable with print_r in my current page and it showing me correct result.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}
<?php $className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1'; ?>
<div class="<?php echo $className; ?>" />
You can create a test.php then run php test.php and you should see the result
<?php
// $count_rows = 1;
$count_rows = 3;
$className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1';
echo "<div class=\"$className\"/>\n";
<div class="<?php '#count_rows#' <= '2')
You are missing a keyword here and also some brackets (which should cause a fatal syntax error), Also you are comparing two different literal strings - surely one of the terms should be a PHP variable?
You can't read back stuff you've previously written to the output stream - you are confusing what is happening in HTML, CSS and PHP.
I think you mean...
<div class="<?php if ($form_fields['count_rows'] <= '2')
Comparing a number by casting it to a string is rather dangerous.
Personally I would do this:
<div class="<?php echo (2 <= $form_fields['count_rows'])
? 'middle_menu' : 'middle_menu1'; ?>">
Since you didn't mention that the script blew up in your face, I suspect there may be a lot of other issues.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}
This is very innefficient. Consider:
$find=array_keys($form_field);
foreach ($find as $index=>$term) {
$find[$index]='#' . $term . '#';
}
$htmlContent = str_replace($find, $form_feld, $htmlContent);

PHP: Show 3 td's of data per table row

I am wanting to use 8 images from my database and load them into a HTML Table. I would like to display 4 images per table row, but however when i run my code below, i seem to get all images in one table row. Any help would be great. Thank you in advance.
$count = $get->rowCount();
if ($count > 0)
{
echo '<table id="" class="uiGrid _51mz _1m6c" cellpadding="2" cellspacing="0">';
$i = 0;
while ($r = $get->fetch(\PDO::FETCH_OBJ))
{
$globals = new \Libraries\Helpers\Views\Globals;
if ($i == 0)
{
echo '<tr class="_51mx">';
}
echo '
<td class="_51m-">
<a href="/e/a/'.$r->data_id.'">
<div class="uiScaledImageContainer _f-u2" style="width:74px;height:74px;">
<img class="scaledImageFitWidth img" src="https://gstatic.acfee.org/akamaihd/i/'.$globals->data_image_name($r->data_id).'">
<div class="_3s6x">
<div class="_50f3"></div>
</div>
</div>
</a>
</td>
';
if ($i > 4)
{
$i = 0;
echo '</tr>';
};
$i++;
echo '
<script type="text/javascript">
$("#favs-preloader").hide();
</script>
';
}
echo '</table>';
put this code directly it will works...
echo '<table id="" class="uiGrid _51mz _1m6c" cellpadding="2" cellspacing="0">';
$i = 0;
while ($r = $get->fetch(\PDO::FETCH_OBJ))
{
$globals = new \Libraries\Helpers\Views\Globals;
$i++;
if ($i == 1)
{
echo '<tr class="_51mx">';
}
echo '
<td class="_51m-">
<a href="/e/a/'.$r->data_id.'">
<div class="uiScaledImageContainer _f-u2" style="width:74px;height:74px;">
<img class="scaledImageFitWidth img" src="https://gstatic.acfee.org/akamaihd/i/'.$globals->data_image_name($r->data_id).'">
<div class="_3s6x">
<div class="_50f3"></div>
</div>
</div>
</a>
</td>
';
if ($i >= 4)
{
echo '</tr>';
$i = 0;
};
echo '
<script type="text/javascript">
$("#favs-preloader").hide();
</script>
';
}
echo '</table>';
In your current code, you're verifying if the $i variable is == 0 in order to add a row. But you're always increasing it's value at the end, even after you set it to zero in the if($i > 4)
Change these lines
if ($i > 4)
{
$i = 0;
echo '</tr>';
};
$i++;
To this:
if ($i > 4)
{
$i = 0;
echo '</tr>';
}
else
$i++;

While loop causing website to vanish

$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query) {
if ($i == "0") { ?><div style="width: 49%; float: left;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } elseif ($i == "1") { ?><div style="width: 49%; float: right;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } $i++; if ($i == "7") { end while; }
}
Why doesn't this code work? If I do it manually without database. You know, just thinking you're PHP and creating the code in HTML and CSS, it works. But as soon as you mix PHP to it, everything goes blank, entire website.
while ($row = mysql_fetch_assoc($sql_query) {
"PHP Parse error: syntax error, unexpected '{' in
As mentioned in comments, you are missing a closing parenthesis (rounded bracket) on your while condition, before the opening brace (squiggly bracket). This should read:
while ($row = mysql_fetch_assoc($sql_query)) {
However, you do have another obvious parse error at the end of your while loop. The following is invalid syntax:
if ($i == "7") { end while; }
This should read:
if ($i == "7") { break; }
"mix PHP and HTML like that" - just don't mix PHP and HTML like that... it's hard to read/maintain.
Regardless of syntax used (conventional or alternative (that Tero Kilkanen suggests) - which is intended to make this type of code easier to read) you simply should not be mixing PHP and output like this anyway, by dropping out/in of PHP parsing mode.
If you need to construct some HTML to be output later then build a string and echo this once at the end of your loop.
So, instead of this:
$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query) {
if ($i == "0") { ?><div style="width: 49%; float: left;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } elseif ($i == "1") { ?><div style="width: 49%; float: right;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } $i++; if ($i == "7") { end while; }
}
Do something like this:
// HTML to be output
$htm = '';
$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query)) {
if ($i == "0") {
$htm .= <<<EOD
<div style="width: 49%; float: left;">
<img id="lookup_designs_item_icon" src="img/designs/{$row["id"]}.jpg" alt="{$row["resolution"]} | {$row["artist"];}"/>
</div>
EOD;
}
elseif ($i == "1") {
$htm .= <<<EOD
<div style="width: 49%; float: right;">
<img id="lookup_designs_item_icon" src="img/designs/{$row["id"]}.jpg" alt="{$row["resolution"];} | {$row["artist"];}"/>
</div>
EOD;
}
$i++;
if ($i == "7") {
break;
}
}
// Output HTML
echo $htm;
The code is now much easier to read at a glance and it quickly becomes obvious that there are further optimisations that can be made. For instance...
the only bit that seems to vary between your if blocks is the float: left / float: right part of your style attribute. So these could be combined.
$i is an integer, yet you are comparing it with a string in your if condition. This works, but is not "correct".
You don't appear to be doing anything in your loop when $i is 2, 3, 4, 5 or 6? So you should be breaking sooner. ie. simply else { break; } would seem to do the same thing?

Second page of pagination displaying ALL results

been stuck on this for hours.
I have a simple (I think) pagination PHP code here working fine for the first page - meaning I get the correct amount of pages displayed and the correct results displayed. Code:
<?php
$query = $_POST ['query'];
$link=mysql_connect('localhost','root','root');
mysql_select_db("asset_catalog",$link);
$q=("SELECT COUNT(*) \"total\" FROM assets WHERE Description LIKE '%$query%' OR Manufacturer LIKE '%$query%'");
$ros=mysql_query($q,$link) or die(mysqli_error());
$row=mysql_fetch_array($ros);
$total=$row['total'];
$dis=15;
$total_page=ceil($total/$dis);
$page_cur=(isset($_GET['page']))?$_GET['page']:1;
$k=($page_cur-1)*$dis;
$q=("SELECT * FROM assets WHERE Description LIKE '%$query%' OR Manufacturer LIKE '%$query%' limit $k,$dis");
$ros=mysql_query($q,$link);
echo "<table border='0'>
<tr>
</tr>";
while($row=mysql_fetch_array($ros))
{
if (($i % 5) == 0) echo "<tr>";
echo "<td><img src='".$row['Image']."' id='queryimg'><br>
<a href='details.php?ID=".$row['ID']."' style='color: #fff;'>{$row[Description]}</a></td>";
if (($i % 5) == 4) echo "</tr>";
$i++;
}
if ( $i > 0 && ($i-1) % 3 < 2) echo "</tr>";
echo "</table>";
?>
<div style="position: absolute; left: 320px;">
<?php
if($page_cur>1)
{
echo '';
}
else
{
echo '<input style="background-color:green;border:1px black solid;border-radius:5px;width:120px;height:30px;color:black;font-size:15px;font-weight:bold;" type="button" value=" Previous ">';
}
for($i=1;$i<$total_page;$i++)
{
if($page_cur==$i)
{
echo ' <input style="background-color:green;border:2px black solid;border-radius:5px;width:30px;height:30px;color:black;font-size:15px;font-weight:bold;" type="button" value="'.$i.'"> ';
}
else
{
echo ' <input style="cursor:pointer;background-color:green;border:1px black solid;border-radius:5px;width:30px;height:30px;color:white;font-size:15px;font-weight:bold;" type="button" value="'.$i.'"> ';
}
}
if($page_cur<$total_page)
{
echo '<input style="cursor:pointer;background-color:green;border:1px black solid;border-radius:5px;width:90px;height:30px;color:white;font-size:15px;font-weight:bold;" type="button" value=" Next ">';
}
else
{
echo '<input style="background-color:green;border:1px black solid;border-radius:5px;width:90px;height:30px;color:black;font-size:15px;font-weight:bold;" type="button" value=" Next ">';
}?>
The problem is if I click on the second page it displays ALL results in the DB - not the results that should be in the second page. Additionally, if I have say 3 pages initially, once I go to the second page it shows me there are 70 pages aka(all the db)
I'm sure there is a quick fix for this but for the life of me I can't figure it out.
Any help, advice would be great. Thank you!
Between pages you lose your $_POST['query'] .
Instead of
$query = $_POST ['query'];
do
$query = (isset($_POST ['query']))?$_POST['query']:$_GET['query'];
or use
$query = $_REQUEST['query'];
AND
in your pagination link replace
'<a href="pagination.php?page='.($page_cur-1).'" style
with
'<a href="pagination.php?page='.($page_cur-1).'&query='.$query.'" style

Categories