I want to create html cards with data from DB - php

I want to create html cards from a db.
I created num_rows that count how many cards it will make, but when I fetch and then echo it only shows the first row. How do I show all rows?
$cas = 0;
while($cas < $number){
$cas++;
echo "
<div class='tbook' align='center'>
<div class='tr'>
<div class=''>$name</div>
<div class=''>$role</div>
<div class=''>$admin</div>
</div>
</div>
";
}

I think its better idea to use foreach, https://www.php.net/manual/en/control-structures.foreach.php
$rows = getDataFromDatabase();
foreach($rows as $row){
echo "
<div class='tbook' align='center'>
<div class='tr'>
<div class=''>$row['name']</div>
<div class=''>$row['role']</div>
<div class=''>$row['admin']</div>
</div>
</div>
"
}

Related

Bootstrap cards stacking vertically

Afternoon all, I'm currently working on a personal project using the bootstrap framework and PHP. Essential what I am trying to achieve is when I pull data from my MySQL database for it to be displayed in the bootstrap card element in horizontal rows of 4 individual cards.
As it stands the technical aspects of pulling data and displaying it works. But when going onto the page, the card elements are stacked. On top of each other vertically in one long list. As it stands, I'm not too sure how to fix this any help would be appreciated.
What it looks like atm
Main Page Code
<?php
include("inc/dbconfig.php");
include("inc/functions.php");
error_reporting(0);
$search = $_POST['search'];
$mysqlQ =("SELECT * FROM cards WHERE cardName LIKE '%$search%'");
$result = $conn -> query($mysqlQ);
if ($result -> num_rows > 0) {
while ($row = $result -> fetch_assoc()) {
itemCard($row);
}
}
else {
echo "<h1 class='search-h1'>No Results Found!</h1>";
echo "<h4 class='search-h4'>It looks like no results could be found, please try again.</h4>";
}
$conn -> close();
Card Function
<?php function itemCard (array $row) { ?>
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-4 col-sm6 col-xs-12">
<div class="card">
<div class="card-img">
</div>
<div class="card-body">
<h5 class="card-title text-center"><?= $row["cardName"] ?></h5>
<p class="text-center">Card Set: <b><?= $row["cardSet"] ?></b></p>
<p class="text-center">Card Set: <b><?= $row["cardRarity"] ?></b></p>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
Note: Currently not using any custom CSS at this stage I was trying to use the default bootstrap functionality for the layout
You are returning a container and a row on each iteration.
You should have a single container and a row generated after 4 cards.
You should print your container and row once before printing items.
Main Page Code
<?php
include("inc/dbconfig.php");
include("inc/functions.php");
error_reporting(0);
$search = $_POST['search'];
$mysqlQ =("SELECT * FROM cards WHERE cardName LIKE '%$search%'");
$result = $conn -> query($mysqlQ);
if ($result -> num_rows > 0) {
# container beginning tags
echo '<div class="container"><div class="row">';
# container content
while ($row = $result -> fetch_assoc()) {
itemCard($row);
}
# container ending tags
echo '</div></div>';
}
else {
echo "<h1 class='search-h1'>No Results Found!</h1>";
echo "<h4 class='search-h4'>It looks like no results could be found, please try again.</h4>";
}
$conn -> close();
Card Function
<?php function itemCard (array $row) { ?>
<div class="col-lg-3 col-md-4 col-sm6 col-xs-12">
<div class="card">
<div class="card-img">
</div>
<div class="card-body">
<h5 class="card-title text-center"><?= $row["cardName"] ?></h5>
<p class="text-center">Card Set: <b><?= $row["cardSet"] ?></b></p>
<p class="text-center">Card Set: <b><?= $row["cardRarity"] ?></b></p>
</div>
</div>
</div>
<?php } ?>

Limit maximum number of <td> elements of a table per line

I want to build a page where I need to show all the members from a database. But when I print them, it shows them on the same line, no matter how much the members are. And I want to limit the number of members per line to 5. How can I do this?
Thank you in advance!
<table id="members-table">
<tr>
<?php
$queryContent = "SELECT * FROM users WHERE member='yes'";
$result = mysqli_query($db_connection, $queryContent);
while($row = mysqli_fetch_assoc($result)) {
echo '<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>' .$row['ShownName']. '</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</td>';
}
?>
First, you should consider not using table elements to align your content. This is an outdated practice and not recommended. Check out this StackOverflow question for some great advice on the subject. In short, using tables for laying out your page contents comes from the earlier days of the web before we had things like flexbox and grid layouts.
To answer your question, though, you should implement a $loop_count variable, and echo "</tr><tr>" each time $loop_count > 0 AND $loop_count % 5 == 0.
You have to write a <tr> tag on each 5 loops, except for the first loop.
Add $num=0. Then, in the loop, check if $num is greater than 1 (not for the first loop), and the modulo % with five is zero.
<table id="members-table"><tr>
<?php
$queryContent = "SELECT * FROM users WHERE member='yes'";
$result = mysqli_query($db_connection, $queryContent);
$num = 0;
while($row = mysqli_fetch_assoc($result)) {
if ($num++ % 5 == 0 && $num > 1) echo '</tr><tr>'; // Change is here
echo '<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>' .$row['ShownName']. '</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</td>';
}
?></tr></table>
The devil is in the detail on this one. Because you are building a table (which must have an equal number of columns in each row) you need to write conditionals to build a complete structure.
First, a set of conditionals to separate the data into rows of 5 cells
Second, a conditional after the loop to ensure that the final table row contains the correct number of cells.
Code: (Demo)
$resultset=[
['ShownName'=>'A'],
['ShownName'=>'B'],
['ShownName'=>'C'],
['ShownName'=>'D'],
['ShownName'=>'E'],
['ShownName'=>'F'],
['ShownName'=>'G']
];
echo "<table>";
$counter=0;
foreach($resultset as $row){ // you while loop
if($counter%5==0){
if($counter){
echo "</tr>";
}
echo "<tr>"; // start new row
}
echo "<td>";
echo "<div class=\"card\">";
echo "<img src=\"img/img_avatar2.png\" alt=\"Avatar\">";
echo "<div class=\"container\">";
echo "<h4><b>{$row['ShownName']}</b></h4>";
echo "<p style=\"font-family:Roboto;\">Architect & Engineer</p>";
echo "</div>";
echo "</div>";
echo "</td>";
++$counter;
}
if($mod=$counter%5){
$colspan=5-$mod;
echo "<td",($colspan>1?" colspan=\"$colspan\"":""),"></td>"; // complete the row with appropriately sized cell
}
echo "</tr>";
echo "</table>";
Output:
<table>
<tr>
<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>A</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</div>
</td>
<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>B</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</div>
</td>
<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>C</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</div>
</td>
<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>D</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</div>
</td>
<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>E</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>F</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</div>
</td>
<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>G</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</div>
</td>
<td colspan="3"></td>
</tr>
</table>
Using the mod operator (%) will do the trick. This will work and not produce extra unnecessary TR's or /TR's (with the exception of a single empty row if the data is blank):
<table id="members-table">
<?php
$queryContent = "SELECT * FROM users WHERE member='yes'";
$result = mysqli_query($db_connection, $queryContent);
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
if ($i % 5 == 0) {
echo "<tr>";
}
echo '<td>
<div class="card">
<img src="img/img_avatar2.png" alt="Avatar">
<div class="container">
<h4><b>' .$row['ShownName']. '</b></h4>
<p style="font-family:Roboto;">Architect & Engineer</p>
</div>
</td>';
if ($i % 5 == 4 || $i - 1 == count($cols)) {
echo "</tr>";
}
$i++;
}
?>

New containing div after every 3 records

I would like to create a new containing <div> after 3 results, using PDO result loop.
For my self-study-project I have to made a product page with bootstrap and after every 3rd record I have to make a new row and show again 3 col-md-4's, etc, etc.
Now I have this as my code:
<div class="row">
<?php
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
?>
<div class="col-md-4">
<div class="product">
<div class="title"><?php echo $row->pname ?></div>
<div class="img"><img
src="../product/img/<?php echo $row->pnumber ?>/<?php echo $row->pthumbnail ?>.jpg?$pop210x210$"/>
</div>
<div class="vijftien"></div>
<div class="deliver">Levertijd: <strong><?php echo $row->pdelivertime ?></strong></div>
<div class="vijf"></div>
<div class="other"></div>
<div class="row">
<div class="col-md-6">
<div class="price"><?php echo $row->pprice ?></div>
</div>
<div class="col-md-6">
<div class="order">
<button class="log_in" id="doLogin">Meer informatie</button>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
I have visited and studied other questions but I do not really get the idea of how they are doing it and how I can implement the correct method into my code.
As tadman stated in the comment under your question. The best approach should use a modulus operator (%) with 3.
Place your separating condition at the start of each iteration. (Demo)
Like this:
$x=0; // I prefer to increment starting from zero.
// This way I can use the same method inside a foreach loop on
// zero-indexed arrays, leveraging the keys, and omit the `++` line.
echo "<div class=\"row\">";
foreach($rows as $row){
if($x!=0 && $x%3==0){ // if not first iteration and iteration divided by 3 has no remainder...
echo "</div>\n<div class='row'>";
}
echo "<div>$row</div>";
++$x;
}
echo "</div>";
This will create:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
Late Edit, here are a couple of other methods for similar situations which will provide the same result:
foreach(array_chunk($rows,3) as $a){
echo "<div class=\"row\"><div>",implode('</div><div>',$a),"</div></div>\n";
}
or
foreach ($rows as $i=>$v){
if($i%3==0){
if($i!=0){
echo "</div>\n";
}
echo "<div class=\"row\">";
}
echo "<div>$v</div>";
}
echo "</div>";
To clarify what NOT to do...
Sinan Ulker's answer will lead to an unwanted result depending on the size of your result array.
Here is a generalized example to expose the issue:
Using this input array to represent your pdo results:
$rows=["one","two","three","four","five","six"];
Sinan's condition at the end of each iteration:
$i=1;
echo "<div class=\"row\">";
foreach($rows as $row){
echo "<div>$row</div>";
if($i%3==0)echo "</div>\n<div class='row'>"; // 6%3==0 and that's not good here
// 6%3==0 and will echo the close/open line after the content to create an empty, unwanted dom element
$i++;
}
echo "</div>\n\n";
Will create this:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
<div class='row'></div> //<--- this extra element is not good
You need to add a new closure tag and open new one every 3th iteration.
<div class="row">
<?php
$sql = "SELECT * FROM products";
$stmt = $conn->query($sql);
$stmt->execute();
$i=1;
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
?>
<div class="col-md-4">
<div class="product">
<div class="title"><?php echo $row->pname ?></div>
<div class="img"><img
src="../product/img/<?php echo $row->pnumber ?>/<?php echo $row->pthumbnail ?>.jpg?$pop210x210$"/>
</div>
<div class="vijftien"></div>
<div class="deliver">Levertijd: <strong><?php echo $row->pdelivertime ?></strong>
</div>
<div class="vijf"></div>
<div class="other"></div>
<div class="row">
<div class="col-md-6">
<div class="price"><?php echo $row->pprice ?></div>
</div>
<div class="col-md-6">
<div class="order">
<button class="log_in" id="doLogin">Meer informatie</button>
</div>
</div>
</div>
</div>
</div>
<?php
if($i%3==0)echo "</div><div class='row'>";
$i++;
} ?>
$x = 0;
echo "";
foreach($rows as $row)
{
/* added one more condition for removing empty div.... */
if ($x != 0 && $x % 3 == 0 && $x < count($rows))
{
echo "</div>\n<div class='row'>";
}
echo "<div>$row</div>";
++$x;
}
echo "";

Bootstrap how to foreach with columns inside

I have a foreach and I want to place 4 columns then break in a new row and start again but for some reason i got the column number 5(test2) bad pushed like this picture:
should be like this:
here is the code to generate that:
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
Secciones
</div>
<div class="panel-body">
<div class="row">
#foreach ($boards as $board)
<div class="col-md-3">
<h3>{{$board->boaName}}</h3>
#foreach ($subboards as $subboard)
#if($subboard->boaId == $board->id)
<ul>
<li>{{$subboard->subboaName}}</li>
</ul>
#endif
#endforeach
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
</div><!--End container-->
Try moving the foreach loop outside of the <div class="row">? If that doesn't work do you think you could mock this up in a jsFiddle example?
You need a test after 4 iterations to close and open again the row div.
If you know how many columns to expect, you could do the following (I've ommited your inner content of each column for my example - I've also left the counter in so you can see the incrementation for testing):
$i = 1;
foreach($boards as $board) {
if($i == 1 || $i == 5 || $i == 9) {
echo "<div class='row'>";
echo "<div class='col-md-3'>" . $i++ . "</div>";
}
elseif($i%4 == 0) {
echo "<div class='col-md-3'>" . $i++ . "</div>";
echo "</div>";
} else {
echo "<div class='col-md-3'>" . $i++ . "</div>";
}
}
What's happening here is if the column count is the 4th iteration, it should echo out an opening <div class="row"> as well as a column. If the current column is divisible by 4, it should echo out a column with an extra closing </div> (to close the row class.)
If the current count is neither of the above, it simply echo's out a column.
You can, of course, mod the above if the amount of potential columns is unknown.

PHP Iterate 12 items perform echo on every third

Hi I have been chasing my tail for a while on this one and wondered if someone could solve my headache.
Basically I am rendering 12 items to the page. Each 3 items need to be wrapped in a row like:
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
Thanks in advance.
Hi I think some code would help:
$i=0;
foreach($posts as $p) {
$i++
}
So basically within the for each I will be outputting a row and 3 items.The results are coming from a database query. I have tried a few different approaches such as
if($i == 1) {echo "<div class='row'>";}
if ($counter % 4 == 0) {
echo "</div><div class='row'>";
}
However I keep failing, please note these are just snippets of code.
You need to use two loops:
// Outer loop for each row
for ($row = 0; $row < 4; $row++) {
echo '<row>';
// Inner loop for the items
for ($item = 0; $item < 3; $item++) {
echo '<item>';
}
echo '</row>';
}
You should have done it yourself. it needs to know very basic of loop.
try like this:
for($i=0;$i <= 3; $i++){ //outer loop for 12 times
echo "<row>"; // start row
for ($j=0;$j<3;$j++){ // inner loops for echoing 3 times
echo "<item>"; //echo item
}
echo "</row>"; // end row
}
demo : https://eval.in/107129
I have used "\n" for new line in demo. if you needed new line then you can use <br />

Categories