I am trying to display something after 3 rows from my database, but having a hard time to get this to work.
this is my code at the moment
<?php
$query = "SELECT * FROM articles ORDER BY id DESC LIMIT 6";
$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
if ($num>0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
echo "DATA FROM DATABASE";
if (($num % 3) == 0) {
echo '<h1>code every 3 rows</h1>';
}
$num++;
}
}
// if no records found
else{
echo "no data found";
}
?>
Currently, this is outputting after every row 1 and 4.
I have tried the following.
if ($num % 3) {
echo '<h1>code every 3 rows</h1>';
}
$num++;
This outputs after rows 2 3 5
I am sure its something simple I'm over looking but any help in pointing me in the right direction would be great.
Your error can be found where you initialized $num. you set it to row count and start increasing the $num in the loop. You code should be refactor like so:
<?php
$query = "SELECT * FROM articles ORDER BY id DESC LIMIT 6";
$stmt = $con->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
//$num should start from 1 and increase in the loop
$num = 1;
if($count>0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "DATA FROM DATABASE";
if( ($num % 3) == 0){
echo '<h1>code every 3 rows</h1>';
}
$num++;
}
}
// if no records found
else{
echo "no data found";
}
?>
You can use ($num - 1) % 3 == 2:
if (($num - 1) % 3 == 2) {
echo '<h1>code every 3 rows</h1>';
}
$num++;
echo "DATA FROM DATABASE";
Example:
foreach (range(0, 6) as $k => $i) {
if (($k - 1) % 3 == 2) {
echo "---\n";
}
echo "$i\n";
}
output:
0
1
2
---
3
4
5
---
6
Or $k % 3 == 2 if you do the echo before:
foreach (range(0, 6) as $k => $item) {
echo "$item\n";
if ($k % 3 == 2) {
echo "---\n";
}
}
Related
I have a loop. I need write to 1 and 8 element a button. How I can do it?
$cnt = 1;
while($r = $now->fetch_assoc()) {
if ($cnt > 6) {
break; //write only 5 elements to 1 iteration
}
if($cnt === 1 || $cnt === 8) { //not working
echo "<button>Send</button>";
}
$cnt++;
}
My condition is now working. How I can do correctly condition to 8 element, which in 2 iterations?
Example, waht I want get:
------Button-------
1) record
2) record
3) record
4) record
5) record
1) record
2) record
3) record
------Button-------
1) record
2) record
....
Maybe I understand your question wrong, but I think that this should achieve it.
$i = 1;
$j = 1;
while($r = $now->fetch_assoc()) {
if ($i > 6) {
$i = 0;
}
if($j === 1 || $j%8 === 0) {
echo "<button>Send</button>";
}
$i++;
$j++;
}
<div>
<?php if ($result->num_rows > 0) {
$i=1;
while($row = $result->fetch_assoc()) {
if( $i % 6 == 0 )
{ ?>
</div>
<div>
<?php } ?>
<h4><?php echo $row["city"] ?></h4>
<h6><?php echo $row["info"] ?></h6>
<?php $i++;
}
} else {
echo "0 results";
}
?>
</div>
Goal: div's with each 6 rows in it.
When I use $i=1, the first gets 5 results and the other ones get 6.
When I use $i=0 the first one is empty and the other ones get 6.
How to get the first div also filled with 6 results?
Try using array_chunk. That way you don't have to worry where to put your div ends and it's more readable:
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
foreach (array_chunk($rows, 6) as $subset) {
echo "<div>";
foreach ($subset as $row) {
echo "<h4>{$row["city"]}</h4>"
echo "<h6>{$row["info"]}</h6>"
}
echo "</div>";
}
Using array_chunk as proposed by #Justinas is a good way to refactor code. Yet, taking your original code, the issue is about where you check printed amount. It is wrong to first check output amount as it breaks the logic for the first iteration. Please, refer to the code below.
<div>
<?php
if ($result->num_rows > 0) {
$i = 1;
while ($row = $result->fetch_assoc()) {
# if ($i % 6 == 0) {
# echo '</div><div>';
# }
# move commented code from above to ...
echo "<h4>{$row["city"]}</h4>";
echo "<h6>{$row["info"]}</h6>";
# ... here
if ($i % 6 == 0) {
echo '</div><div>';
}
$i++;
}
} else {
echo "0 results";
}
?>
</div>
You can try setting $i = 0 then excluding it in your if statement with
if ($i > 0 && $i % 6 == 0)
since 0 % 6 == 0.
My code is below:
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
$i++;
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
}
echo '</div>';
}
}
portfolio_gallery();
I wanted to echo </div><div> for every after 9th item of the loop but every time I executed the code, the first echo only happened after 8 items instead of 9, but the rest was every 9th.
You have to increment
$i
after
if($i % 9 == 0)
follow the syntax example i worked out its working
<?php
$j=0;
for($i=0;$i<=50;$i++)
{
if($j==9)
{
echo $j.'hioiiiiiii<br/>'; //echo "</div><div>";
$j=-1;
}
$j++;
}
?>
Please try this :)
<?php
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++;
}
echo '</div>';
}
}
declare $i = 1 and Write $i++ at the end of while loop.
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 1; // declare $i = 1 here
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 1){ // 10 , 19 ,28
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++; // increment at end of the loop
}
echo '</div>';
}
I was able to solve it by modifying the condition:
So instead of: if($i % 9 == 0) {...}
I used: if($i!=0 && $i % 9 == 0) {...}
And also placing $i++ at the end of while loop.
Short
Generating table with barcodes of items. Each item has exact quantity in database table. Fields in tables are limited: 65, if more then 65 then build a second table, then a third one...How to generate tables with this conditions?
Detailed
Let's say we want to generate a table with 65 available fields (5x13).
My plan is the following
User selects items' checkboxes
When user submits form, PHP gets values of checked checkboxes
PHP gets quantities of each item from database
Generating table
For ex. the quantity for item id 55 is 2 and for 56 is 4 then the table must look like that
My code looks like that (I know that it's wrong, but I can't figure out how it must be. There must be more than 5 counters: rows counter, columns counter, $_POST['id'] counter, items' quantity counter, table counter (if total sum is more than 65))
UPDATE
<?php
$items = array();
foreach ($_POST['checkbox'] as $id) {
$stmt = $db->prepare("SELECT `qt` FROM `items` WHERE `id`=?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($qt);
$stmt->fetch();
$stmt->close();
for ($cnt = 1; $cnt <= $qt; $cnt++)
$items[] = $id;
}
$i = 0;
foreach ($items as $item) {
for ($j = 0; $j < $item['quantity']; $j++) {
// check if it's the beginning of a new table
if ($i % 65 == 0)
echo '<table>';
// check if it's the beginning of a new row
if ($i % 5 == 0)
echo '<tr>';
echo '<td><img src="bc.php?id=' . $item['id'] . '" alt="' . $item['name'] . '" /></td>';
// check if it's the end of a row
if (($i - 1) % 5 == 0)
echo '</tr>';
// check if it's the end of a table
if (($i - 1) % 65 == 0)
echo '</tr></table>';
$i++;
}
}
// if the last row wasn't closed, close it
if ($i % 5 != 0)
echo '</tr>';
// if the last table wasn't closed, close it
if ($i % 65 != 0)
echo '</table>';
?>
Any suggestion?
EDIT 4
<?php
$i = 0;
foreach ($_POST['checkbox'] as $id) {
$stmt = $db->prepare("SELECT `qt` FROM `items` WHERE `id`=?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($qt);
$stmt->fetch();
$stmt->close();
for ($cnt = 1; $cnt <= $qt; $cnt++) {
// check if it's the beginning of a new table
if ($i % 65 == 0)
echo '<table>';
// check if it's the beginning of a new row
if ($i % 5 == 0)
echo '<tr>';
echo sprintf('<td><img src="bc.php?id=%1$d" alt="%1$d" /></td>', $id);
// check if it's the end of a row
if (($i + 1) % 5 == 0)
echo '</tr>';
// check if it's the end of a table
if (($i + 1) % 65 == 0)
echo '</table>';
$i++;
}
}
// if the last table isn't full, print the remaining cells
if ($i % 65 != 0) {
for ($j = $i%65; $j < 65; $j++) {
if ($j % 65 == 0) echo '<table>';
if ($j % 5 == 0) echo '<tr>';
echo '<td></td>';
if (($j + 1) % 5 == 0) echo '</tr>';
if (($j + 1) % 65 == 0) echo '</table>';
}
}
You need to just repeatedly make sheets of 65 cell tables until you're done.
I'm going to pseudo code:
data rows = resultOfMyQuery();
int index = 0;
while(index < rows.count()) {
index = createASheet(rows, index);
}
END;
int createASheet(data rows, int index) {
int availableCells = 65;
int column = 0;
print("<table>");
while (availableCells > 0) {
if (index < rows.count()) {
data row = rows.get(index);
int quantity = row.getQuantity();
if (quantity > availableCells) {
// Stay on this item with reduced quantity for next sheet.
row.setQuantity(quantity - availableCells);
rows.set(index, row);
} else {
// Move on to next item on this (or next) sheet.
index++;
}
for (i=0; i<quantity && availableCells>0; quantity--) {
column = makeACell(column, StringFormat("<TAG ATTRIB='%d'></TAG>",row.getId()));
availableCells--;
}
} else {
// fill in empty cells
column = makeACell(column, "");
availableCells--;
}
}
print("</table>");
return index;
}
int makeACell(int column, String filling) {
String cell = "";
if (column == 0) {
cell.append("<tr>");
}
cell.append("<td>").append(filling).append("</td>");
if (column == 4) {
cell.append("</tr>");
}
print cell;
return (column+1) % 5;
}
Why don't you use an existing barcode system like QR-codes? These standards offer libraries to build the codes and are readable by various devices.
If you really want to built your own barcode I strongly suggest to use the binary system to store your values. Think about check sums too.
Pretty much I have a code like below that I'm trying to add </tr><tr> to after every 6 results.
echo "<table><tr>";
$query="SELECT * WHERE id='$id' ORDER BY date ASC";
$result=mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($rts = mysql_fetch_array($result)){
$cdata1 = $rts['cdata1'];
$cdata2 = $rts['cdata2'];
echo "<td>$cdata1 and $cdata2</td>";
}
}else{
echo "<td>no results</td>";
}
echo "</tr></table>";
echo "<table><tr>";
$query="SELECT * WHERE id='$id' ORDER BY date ASC";
$result=mysql_query($query);
$i = 0;
if (mysql_num_rows($result) > 0) {
while($rts = mysql_fetch_array($result)){
$cdata1 = $rts['cdata1'];
$cdata2 = $rts['cdata2'];
echo "<td>$cdata1 and $cdata2</td>";
if(++$i % 6 == 0) {
echo '</tr><tr>';
}
}
}else{
echo "<td>no results</td>";
}
echo "</tr></table>";
UPD:
Whats means if(++$i % 6 == 0) code:
++$i equals $i = $i + 1;
$i % 6 means $i modulo 6
If $i modulo 6 equals 0 then echo </tr><tr>
So we can write it as:
$i = $i + 1;
if($i % 6 == 0) {
echo '</tr><tr>';
}
http://php.net/manual/en/internals2.opcodes.mod.php
http://php.net/manual/en/language.operators.increment.php