how to put div in a for loop - php

For parsing a list of articles, i have this code to parse all the articles:
while($article = $articles->fetch())
{
$date = strtotime($article['createdAt']);
$formatted_date = date("F Y",$date);
?>
<br />
<div class="news-content">
<div class="news-image">
<?php echo $article['title']; ?>
</div>
<div class="news-article">
<h3>
<span><?php $date = strtotime($article['createdAt']); echo /*date("F j",$date);*/ strftime('%e %B',$date) ?></span>
<br />
<?php echo $article['title']; ?>
</h3>
</div>
</div>
<?php
} //end while loop
?>
What i want to achieve: only the first 5 <div class="news-content">...</div> should be shown.
I know i have to do something with a for loop
but i do not know exactly how to use the for loop for this situation...
Can someone help me with that?

There are a lot of different ways to limit a loop. One possibility is to use a for loop instead of a while loop. for is often a good option if you want something to happen a specific number of times. Adding something else like fetch into the continuation condition will mean it happens up to a specific number of times.
for ($i = 0; $i < 5 && $article = $articles->fetch(); $i++) {
// output article
}

Related

How to count the arrays from a result of a query? [duplicate]

This question already has answers here:
Echo current number of row
(3 answers)
Closed 1 year ago.
I have a query that I make using PHP and it returns me all the rows that satisfied the condition that was given, now, I'm wondering if there's a way to count each number of row a result of a query has and pass that number to an id of an element on HTML?
<?php
$res2 = mysqli_query($con,"SELECT NAME, PRICE FROM product WHERE AVAILABLE = 1 AND ID_CATEGORY = 17");
?>
<body>
<?php
while($row = mysqli_fetch_row($res2)) {
print_r($row);
?>
<div class="item">
<img class="trj_img_cls" src="RSC/COMING_SOON.jpg" alt="" id="imgDG<?php ?>">
<div class="texto_trj">
<div class="nombre_producto">
<h2 id="ttlDG<?php ?>">título</h2>
</div>
<div class="precio_producto">
<i class="icon-dollar"></i>
<label id="prDG<?php ?>">0.00</label>
</div>
<div class="caracteristicas">
<ul id="caractDG<?php ?>"></ul>
</div>
</div>
</div>
<?php
}
?>
</body>
I put <?php ?> because there I want to add the variable (number of the row) so it complements the actual id and then i'm able to look for that id with javascript. Another thing is that I use the print_r() just to see if the elements were appearing.
This can be done by setting an $increment variable to 1 at the start of the while loop, and incrementing it at the end of the loop.
<?php
$increment = 1;
while($row = mysqli_fetch_row($res2)) {
And then using it like this:
id="imgDG<?php echo $increment; ?>">
And then incrementing it at the end:
<?php
$increment++;
}
?>

Subtracting DB values via php

I am trying to subtract values of a db table $activationFee from a users total balance . How may i add the subtraction in the code below:
<div class="number">
<strong>
<?php echo $settings->currency; ?>
<?php BalanceSystem($user_id); ?>
</strong>
</div>
function BalanceSystem($user_id){
$user_bank = DB::table('bank')->where('userid', $user_id)->first();
echo $user_bank->balance;
}
Can someone please point me in the right direction?
I tried <?php BalanceSystem($user_id) - $activationFee ; ?> but did not work ... hides
You should not echo inside a function, it will prevent situations like this, where you try to substract a value to an output.
<div class="number">
<strong>
<?php echo $settings->currency; ?>
<?php echo BalanceSystem($user_id); ?>
</strong>
</div>
function BalanceSystem($user_id){
$user_bank = DB::table('bank')->where('userid', $user_id)->first();
return $user_bank->balance;
}
//Substract
<?php echo (BalanceSystem($user_id) - $activationFee); ?>
This is how I managed to solve it:
function BalanceSystem($user_id){
$user_bank = DB::table('bank')->where('userid', $user_id)->first();
$total = $user_bank->balance - 100;
echo $total;
}

How to clean up this strange PHP code?

this script outputs the birthdays as headlines and the customer(s) below.
So the output is "grouped" by the date of birth.
echo "<div>";
foreach(pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty)) as $row)
{
if(!isset($birthday) or $birthday != $row['birthday'])
{
unset($drawline);
echo "</div>";
echo "<div class=title><h1>".$row['birthday']."</h1></div><div class=customer>";
}
if(isset($drawline)){echo "<hr>";}
echo $row['customer']."<br>";
$drawline = 1;
$birthday = $row['birthday'];
}
echo "</div>";
'birthday' is a DATE-field in the database.
Between the customers there's always a line (hr), but not after the last customer of a d.o.b.
Example output:
<div class=title><h1>1986-10-08</h1></div>
<div class=customer>
Don Foo<br>
<hr>
Joe Bar<br>
</div>
<div class=title><h1>1988-03-18</h1></div>
<div class=customer>
Jane Fonda<br>
<hr>
Elvis Burns<br>
</div>
Is it possible to remove the <div> and </div> outside the foreach()?
It produces always an empty <div></div>.
I've decided that it's too much hassle on the programmer's mind to see what's happening here, so here is much cleaner version of your code.
<?php
$people = pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty));
if (!empty($people)) {
// Find out people with the same birthday and group them.
$birthdays = [];
foreach ($people as $man) {
$birthday = $man['birthday'];
if (empty($birthdays[$birthday])) {
$birthdays[$birthday] = [];
}
$birthdays[$birthday][] = $man['customer'];
}
// Now let's output everything!
?>
<div>
<?php foreach ($birthdays as $birthday => $customers): ?>
<div class=title><h1><?= $birthday ?></h1></div>
<div class="customer">
<?= implode('<br><hr>', $customers) ?>
</div>
<?php endforeach;?>
</div>
<?php } // endif (!empty($people)) ?>
Main point of this solution - very simple to understand, uses somewhat templating (you could create one for this little snippet), easy to debug and modify. And yes, it does not output the empty <div></div> anymore!

PHP echoing a specific amount of rows

I have a table in my database with 100 names, dates, id's, and other stuff. I want to be able to get a specific amount of rows echoed in a div, and then another specific amount in the next and so on.
I have been looking at foreach and break here, cause my googling kind of sent me there.. but maybe im looking at the wrong thing:
http://php.net/manual/en/control-structures.break.php
I just don't seem to get things right.
This is a school project and I know this is maybe a little bit vague, sorry about that.
Something like this:
<div id="div1"> echo row 1-7 </div>
<div id="div2"> echo row 7-19 </div>
<div id="div3"> echo row 20-44 </div>
and so on...
Could someone point me in the right direction?
You can do it directly in your query
Use at the end of your query this:
<div id="div1"> echo row 1-7 </div> use "LIMIT 0,6"
<div id="div2"> echo row 7-19 </div> use "LIMIT 7, 19"
<div id="div3"> echo row 20-44 </div> use "LIMIT 20,44"
if you have a numerically indexed array holding your rows you could do something like:
<div id="div1">
<?php for ($i = 1; $i <= 7; $i++) {
print $yourArray[Si]['some_field'];
} ?>
</div>
<div id="div2">
<?php for ($i = 8; $i <= 19; $i++) {
print $yourArray[Si]['some_field'];
} ?>
</div>
...
Something like this (not tested) might work:
$id=1;
$count=0;
$limit=20;
foreach($row as $r){
if ($count==0) echo "<div id='div$id'>";
echo $r;
if ($count++==$limit){
$count=0;
$id++;
echo "</div>\n";
};
}
if ($count!=0) echo "</div>";

why am I getting unexpectedly repeated results from my php file?

Yes, I've looked around and yes I've used mysql_fetch_array hundreds of times successfully before. I want a php file that will output an html file with some constants and a few interpreted php variables. After an hour, this is where I'm at.
<?php
require "(this is sql statement to get all rows from the db).php";
$i = 1;
while($row = mysqli_fetch_array($results_getpieces) && $i < 11 ){ ?>
<li>
<a href="#image-1">
<img src="<?php echo $row['content']; ?>" alt="image01">
<span><?php echo $row['title']; ?></span>
</a>
<div class="lb-overlay" id="image-1">
<img src="<?php echo $row['thumb']; ?>" alt="image01" />
<div>
<h3>blahblah <span>bluelue</h3>
<p>sherpas don't dance</p>
Prev
Next
</div>
x Close
</div>
</li>
<?php
$i++;
}
?>
When I display the $row results in a table, there's no problem. Before I added that i++ business, I could get the first record from my results, but it would just repeat those results for all ten instances.
Help almighty stackers, and overflow me with your knowledge. Please. I can't go to sleep until I get this. Where am I going wrong?
You need to parenthesize the condition appropriately, so that the array that you get back from the function call doesn't get "and"-ed with the condition "$i < 11":
($row = mysqli_fetch_array($results_getpieces)) && $i < 11

Categories