How to create new DIV every 8 MySQL rows queried - php

im trying to figure out how to create new DIV every 8 MySQL rows queried. I am integrating jPagination into my site and so I need to create a new DIV container every 8 rows it receives from the database. Any ideas?

you need this: %
not sure about how your code exactly goes, but in the loop of every row you make a count++ and then something like this which would be in C:
if(!count%8) {
print DIV eccc
}
just so you understand what this % does: it gives you the remainer of a division. For example, if your row is number 20, so count equals to 20 at that moment, 20%8 will equal 4. That is because if you divide 20/8 you will have 2.** something, then multiply 2*8 you get 16. Take 20-16 = 4. So 20%8 is 4. Only when the number in count++ is perfectly divisible by number 8 you will get 0 zero there. So your IF statement says: if there ia no remain dividing count by 8 then do this
maxim

i = 1
while( gettingRows )
{
doWhateverYouDoHere()
if ( i%8 === 0 )
print "div"
++i
// or put increment right into the if statement like ( if i++ % 8 === 0 )
}

<?php
// previous code.....
$counter = 1;
echo '<div class="outercssclass">';
echo '<div class="innercssclass">';
// fetch mysql query data into $results....
// you can do validations with mysql_num_rows to check the number of rows the query returned
foreach($results as $result) {
$counter++;
if($counter % 8 == 0) {
echo '</div><div class="innercssclass">';
}
// other logic...
// rest of the code
}
echo '</div>'; // for closing the inner div
echo '</div>'; // for closing the outer wrapper div
// rest of the program logic...

Related

Php/Jquery add rows while looping through data

I have a database with "7" user account objects.
I have called the objects using any of the loop functions.
foreach (objects as object) {
echo '<div class="col-4>"'.object->property.'"</div>';
}
I want to add rows for each 3 columns as they are being displayed.
The above code would result in all my objects/colums/divs being nested in one row.
I want a way in which I can have the loop adding a row for every 3 columns.
Count the objects as you go. If $x divided by 3 has no remainder, close and open the next div:
$x = 0;
foreach ($objects as $object){
$x ++;
echo '<div class="col-4">"'.$object->property.'"</div>';
echo ($x % 3 == 0) ? '</div><div class="row">' : '';
}

Php Array Count to run script run for each reply till 3rd reply and not more than that

I have a Forum in which adscript is displayed after every reply
<?php if( count( $replies ) <= 3 ){ ?>
---- script ----
<?php } ?>
Earlier there was a clause that there could be maximum 3 replies per Forum post - but now that clause is changed and there are 5, 7 or 10 replies even
I want to modify code so EVEN If there are more than 3 replies - then script should run after each reply till 1st 3 replies and not from 4th reply onwards
I believe an array is to used likely
<?php
$replyCount = 0;
foreach( $replies as $reply )
{
$replyCount++;
$replyNumber = array(1, 2, 3);
if (in_array($replyCount, $replyNumber)) {
echo "script";
}
?>
But - what the above script is doing is that
Its displaying the script in all replies
Its displaying script 3 times after each reply
Can some one help and advise in modification so that
Script should run once after each reply
Script should run till 3rd reply and not more than that
Pls help and advise
add break; after echo 'script'.
You said:
Its displaying the script in all replies
Its displaying script 3 times
after each reply
That's because your for loop is doing 3 iterations since on the first iteration replyCount gets value of 1, is 1 in the array? yes.
Second iteration replyCount gets value of 2 etc etc.
EDIT:
Answer to your comments:
<?php
/* CASE Where number of replies is 3 or less. */
/* Prints "script" 1 extra time than count($replies) */
$counter = 0;
if(count($replies) <= 3) {
foreach($replies as $reply) {
if(count($replies) == $counter) {
break;
}
else {
echo "script";
}
$counter++;
}
}
/* CASE Where number of replies is 4 or more print script 3 times. */
else {
echo 'script' . '<br />';
echo 'script' . '<br />';
echo 'script' . '<br />';
}
?>
Please read the current code posted here and then see the cases:
Case 1: count($replies) = 0
foreach loop starts
first IF fires, nothing happens
Case 2:
count($replies) = 1
foreach loop starts
go into else
print script
$counter is now 1
count($replies) == $counter
stop loop
result is that we have 'script' printed 1 time.
Case 3: count($replies) = 2
foreach loop starts
go into else
print script
$counter is now 1
go into else
print script
$counter is now 2
count($replies) == $counter
stop loop
result is that we have 'script' printed 2 times.
Case 4: count($replies) = 3
foreach loop starts
go into else
print script
$counter is now 1
go into else
print script
$counter is now 2
go into else
print script
$counter is now 3
count($replies) == $counter
stop loop
result is that we have 'script' printed 2 times.
Case 5: count($replies) > 3
result is that we have 'script' printed 3 times.
These are the results if you go over the iterations of this foreach loop.

Reduce a Value from Each Iteration of Foreach in PHP

I am trying to redeem a value from the array. For example I have 20 Points and I am going to redeem from the list of earned points.
Here is my array structure which will shown as follows
$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'0'),
array('earnedpoints'=>'25','usedpoints'=>'0'),
);
which has n number of data's(array).
I am trying to reduce the values from the earned points
Points to redeem : 20. In a foreach statement i am just
$remainingpoints=20; // Redeeming Points is named as in variable of $remainingpoints
foreach ($newstructure as $keys => $newone) {
if ($remainingpoints > $newone['earnedpoint']) {
$remainingpoints = $remainingpoints - $newone['earnedpoint'];
} else {
$remainingpoints = $newone['earnedpoint'] - $remainingpoints;
}
}
For the Point Redeeming for the first iteration of foreach earned point is 10, remaining point is 10 (based on above code) and used point is 10
For the second iteration the earned point is 25 but i want to redeem only 10 so i want to stop the loop once the redeeming values are finished (Previous Iteration 10 and Current Iteration 10)
I trying to get the result as (Redeem Point 20)
First Iteration Used Points 10 and Remaining Points is 10.
Second Iteration Used Points 10 and Remaining Points is 0.
Also I am trying to store the information as in the form of array too.
$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'10','remainingpoints'=>'10'),
array('earnedpoints'=>'25','usedpoints'=>'10','remainingpoints'=>'0'),
);
Can anyone point me a right direction inorder to get this desired result?
First thing, in one place you use earnedpoints as your table key, and in loop you use earnedpoint.
This code should work for you:
<?php
$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'0'),
array('earnedpoints'=>'25','usedpoints'=>'0'),
);
$remainingpoints=25; // Redeeming Points is named as in variable of $remainingpoints
foreach ($newstructure as $keys => $newone) {
if ($remainingpoints > $newone['earnedpoints']) {
$toRedeem = $newone['earnedpoints'];
}
else {
$toRedeem = $remainingpoints;
}
$remainingpoints -= $toRedeem;
$newstructure[$keys]['usedpoints'] = $toRedeem;
$newstructure[$keys]['remainingpoints'] = $remainingpoints;
/*
if ( $remainingpoints == 0 ) {
break;
}
*/
}
var_dump($newstructure);
In comment I put code where you could break your loop but when you break it, you won't have set used_points and remainingpoints for the following array values

Function returns undefined offset error

I'm trying to resolve the undefined offset. I've Google and looked through stack overflow, but the examples I've found either didn't apply or were too complex for someone of my skill to fathom at this time. I'm very green, but I'd done diligence I promise before asking for help and wisdom.
This is the function as it now exists:
function PrintFolio($aaPh) //aaPh =associative array place holder
{
//print out X number rows of unto 4 images from array with X items
//if array had 7 items, print one row of 4 next row 3
//if array had 16 items, print 4 rows of 4, etc.
//if array had 13 items, print 3 rows of 4, final row with one item
$itemsCount = sizeof($aaPh);//get size of array
$height = (int)ceil(sizeof($aaPh)/4);//rounded up division by 4
//$height = $height + 1;
$keys = array_keys($aaPh); //get keys
//loop through array of X items, for each group of 4 print as a row
for($row = 0; $row < $height; $row++) //looping through the rows
{
echo '<div class="row flush">'; //open div
for($image = 0; $image < 4; $image++) //each row is composed of 4 images
{
$aaPhIndex = array_keys($aaPh)[$row*4+$image]; //if associative array
if( $row*4+$image < $itemsCount ) {
$aaPhIndex = $keys[$row*4+$image];
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
//$template = '<div class="3u"><img src="_img/thumbs/%1$s" alt="" title="%2$s" /></div>';
}
}
echo '</div>'; //end div group of 4
}//end loop
}//end function
It takes an array, slices it up in to units of four and then prints the array as a series of images to the screen. But if I don't have a number which is exactly devisable by 4, it will display whatever open slots remain as undefined offset errors (I hope I am saying that correctly).
My goal is to not have the undefined offset errors print to these screen without revising my site error reporting capabilities (I think doing that would be cheating as it wouldn't correct the problem, just hide it which doesn't seem very above board to me).
Why don't you just put a line break after each 4th element?
function PrintFolio($aaPh) //aaPh =associative array place holder
{
//loop through the array
for($row = 0; $row < Count($aaPh); $row++) //looping through the rows
{
if (!$row || !($row%4)) {
if ($row) echo '</div>'; // close previously opened divs
echo '<div class="row flush">'; //open div
}
/* show your picture code here */
}//end loop
echo '</div>';
}//end function
Here is an update after your comments.
Because you do not need values of your associative array, only keys, the code can be changed as follows:
function PrintFolio($aaPh) //aaPh =associative array place holder
{
//loop through the array
$row=0;
foreach(array_keys($aaPh) as $img) //looping through array keys only
{
if (!$row || !($row%4)) {
if ($row) echo '</div>'; // close previously opened divs
echo '<div class="row flush">'; //open div
}
echo '<img src="' . $img . '">';
$row++; // increase row counter.
}//end loop
echo '</div>';
}//end function
Make sure to put proper path into the tag
Since you can't assume that you're always going to have a number of elements that's exactly divisible by four, you need to test each one. In your inner loop where you calculate the index and then use it to refer to the array, just add a check to ensure that array element exists. From this:
$aaPhIndex = $keys[$row*4+$image];
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
To this:
$aaPhIndex = $keys[$row*4+$image];
if (isset($aaPh[$aaPhIndex])) {
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
}
The error in your logic is that on this line
for($image = 0; $image < 4; $image++) //each row is composed of 4 images
You assume there are always 4 images. But like you said yourself, if the array has for example 13 items, then the last row will only contain one image. This will cause $aaPhIndex = array_keys($aaPh)[$row*4+$image]; to access an array index that doesn't exist.
To solve the problem you will either have to modify $image < 4 to also account for the last row, or just check that the index doesn't exceed the item count. For example by placing the error line under the condition that you already wrote:
if( $row*4+$image < $itemsCount ) {
$aaPhIndex = array_keys($aaPh)[$row*4+$image]; //if associative array
$aaPhIndex = $keys[$row*4+$image];
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
//$template = '<div class="3u"><img src="_img/thumbs/%1$s" alt="" title="%2$s" /></div>';
}
Hope this works

Generate Random Numbers check if same value at db column's value if not loop

I've checked a lot of solutions regarding about looping still, can't apply to my problem.
Still confused about looping though. I want to generate random number then check if the generated number is equal to the content of the table column if it's the same it would generate again until it does not have the same value.
Hope you guys help me, so here we go.
I have a table in database which called "list" it has a structure of id and img
it contains value of
list table:
id | img
1 | 1
2 | 2
3 | 3
4 | 4
number.php
$new_array = array();
$query = "SELECT img FROM list";
$query = mysql_query($query);
while ($query_get = mysql_fetch_array($query)) {
$new_array[] = $query_get[0]; //Store img values into an array
}
$rand = rand(1,5); //Generates random number 1 to 5
$search_r = array_search($rand, $new_array); //Checks if the random number has the same value to the array
while($search == "") { //Until random number gets number 5 it would stop looping
$rand = rand(1,5);
}
echo $rand; //and echo the number 5 here.
Still the result is non-stop loading screen at my browser
Well I have this piece of code to determine if the random number and the array has the same value. But it's only good at one loop.
if (array_search($rand,$new_array)) {
echo "random number has the same value inside the array" . $rand;
} else {
echo "random number does not have the same value inside an array" . $rand;
}
To cut the story short, the values in my table img is 1,2,3, and 4 and I'm generating numbers 1 to 5. Until the generated numbers output 5 it would echo. If the generated numbers get 1 to 4 it would generate again until it gets 5.
Use a do...while loop:
do {
$rand = rand(1, 5);
} while (in_array($rand, $new_array));
Although I'm not sure why you need to generate a random number like this. Why do you need this number?
A recursive function maybe useful in this scenario.
inside function create a random string
Check it in database
If exists then move call recursive function again
else return string

Categories