I am populating an HTML table from a SQL database using php. What I want to do is, I want to limit the number of columns in one row to 4. I tried doing it with CSS using
table.posts{
border:10px;
width:100%;
columns:auto 4;
-webkit-columns:auto 4;
This is the code I have:
<table class="posts">
<tr>
<?php
$respost = mysqli_query($link,"SELECT * FROM posts WHERE post_author=$uid");
while($rowpost = mysqli_fetch_array($respost)) { ?>
<td>
<h3><?php echo $rowpost['post_title']; ?></a></h3>
<h4><?php //echo $rowpost['post_content']; ?></h4>
</td>
<?php
}
?>
</tr>
</table>
There is no problem with the data I get from the db. It's just that it all shows in one row. I want to limit this to just 4 items per row and then break and continue on the next row. What is a simple way to do this?
Try like this
<table class="posts">
<?php
$respost = mysqli_query($link,"SELECT * FROM posts WHERE post_author=$uid");
$row_count=0;
$col_count=0;
while($rowpost = mysqli_fetch_array($respost)) {
if($row_count%4==0){
echo "<tr>";
$col_count=1;
}
?>
<td>
<h3><?php echo $rowpost['post_title']; ?></a></h3>
<h4><?php //echo $rowpost['post_content']; ?></h4>
</td>
<?php
if($col_count==4){
echo "</tr>";
}
$row_count++;
$col_count++;
}
?>
</table>
Related
I have a Loop which is outputting data into a html form and table. How can I limit the number of columns it displays, the reason i wanna do this is because i have limited space and the loop might run for 1000 times or even more depending on the user.
I want to Limit the Columns to say 6, so if the loop runs 6 times I want it to create a new row for another 6 columns and repeat again.
<form method="POST" action="script.php">
<table><tr>
<td><input type="checkbox" name="itemSelect[]" class="itemSelect" value="<?php echo $id; ?>" /></td>
<td>
<div class="item-box" data-id="<?php echo $id; ?>">
<img src="<?php echo $value['image_inventory']; ?>.png">
<div id="rarity">
<p> <?php
if (!isset($value['item_rarity'])) {
$rarity = "common";
echo $rarity;
} else {
$rarity = $value['item_rarity'];
echo $rarity;
}
?> </p>
</div>
</div></td>
</tr> </table>
<?php
}
}
?>
</table>
<button type="Submit">
Send Trade Offer
</button>
this should help, adjust the columns as needed:
<?php
$data = array_fill(0,100,"text");
$i = 0;
$columns = 8;
$rest = $columns-(count($data)%$columns);
?>
<table>
<tr>
<?php foreach($data as $cell): ?>
<?php if(!($i%$columns)) echo '</tr><tr>'?>
<td><?= $cell ?></td>
<?php $i++;?>
<?php endforeach;?>
<!-- fill rest cells-->
<?php if($rest<$columns):for($r=0;$r<$rest;$r++): ?>
<td>fill</td>
<?php endfor;endif; ?>
</tr>
</table>
P.S- could be a better Idea to not use a table at all and just float each "cell" left (use a div element for example) that way the layout would be responsive
I have 2 SQLite- tables, one containing articles and one containing image URL's.
What I'd like to do is to do a foreach() to show the articles in order and show a set number of random images next to the article.
The images should be selected by checking similarity between the Article's and image's categories (column in the table) and then randomized. (The article catergory could be for example 'motorboats' and the img category 'boat').
How do I show the results from two different arrays?
The code for the articles is:
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
<?php foreach($res as $article): ?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?>
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
To add the second array, I tried this, which didn't work, it only showed the results from the first array multiple times:
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt2 = $db->prepare('SELECT * FROM Object;');
$stmt2->execute();
$res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
<?php foreach($res as $article): ?>
<?php foreach($res2 as $object): ?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?><br>
<?php echo $object['img'];?> <!-- For testing. The images should be filtered and a a few random images would be shown here -->
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
I guess it's not possible to use nested foreach() like this.
How will I manage this?
Also, If anyone knows on top of their head how to match the similarities between the arrays as described above, I'd be greatful. If not, I'll deal with this later.
You can fall a function inside the first foreach a pass category of the article to that function. Now in that functino collect all images in an array related
to the passed category and then return it by randomizing it. Code below ..
<?php foreach($res as $article): ?>
<?php
$img = get_img($article['category']);
?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?><br>
<img src="<?php echo $img; ?>" /> <!-- The return result will be shown here -->
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
<?php
function get_img($category){
$stmt2 = $db->prepare('SELECT * FROM Object WHERE category = '.$category);
$stmt2->execute();
$res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$rnd = array();
foreach($res2 as $object){
$rnd[] = $object['img'];
}
$n = rand(0,(count($rnd)-1));
return $rnd[$n];
}
?>
I have a SQLite- file with values.
I get those values and display them in a table of 2 columns:
<?php
$db = new PDO("sqlite:$dbPath");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$stmt = $db->prepare('SELECT * FROM Object;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<table id="table1">
<caption><em>caption</em></caption>
<?php foreach($res as $objekt):
$imageFile = basename($objekt['image']); ?>
<tr>
<td><?php if(isset($objekt['image'])): ?>
<figure class="objectPicture center">
<img src="img/bmo/250/<?php echo $imageFile;?>" alt="<?php echo $objekt['title'];?>">
<?php else: ?>no picture.<?php endif ?><br>
<figcaption><?php echo $objekt['title']; ?>
</figcaption>
</figure>
</td>
<td><?php echo $objekt['text']; ?><br>
<?php echo $objekt['owner']; ?></td>
</tr>
<?php endforeach; ?>
</table>
What I'd like to do is to show the next foreach-loop (values of row2 in the SQLite- file) in another 2 columns next to the first result. And the 3rd loop under the first one and so on.
How do I do that? (total newbie to PHP and SQL here, in case you didn't notice)
The results now:
What I want:
3 Changes to make
Add $idx to foreach loop
<?php foreach($res as $idx => $objekt):
Wrap if around <tr>
<?php if($idx % 2 == 0) { ?>
<tr>
<?php } ?>
Wrap if around </tr>
<?php if($idx % 2 == 1) { ?>
</tr>
<?php } ?>
The above code doesn't consider the case when row number is odd
Hey guys ok so i'm wokring on a clients Weekly Newsletter i'm working with Joomla 2.5.19 and using the enterprise version of acymailling to send it out. I'm kicking my heading in at the moment because of outlook, i'm using a module from Jreviews that publishes the latest reviews submitted to the site in the newsletter, it all works fine except in outlook.
the out put of the script is meant to be a 2x2table with the 4 latest reviews in it. the only prob is outlook seems to hates me using Div for a table and stacks the 2x2 table into a verticle kaotic mess.
the code i'm trying to edit is:
'>
<?php /* root element for the items */ ?>
<div class="jrModuleItems <?php echo $orientation . ' jrThumbnail'.ucfirst($tn_position); ?>">
<?php /* new page starts here */
$pages = array_chunk($reviews,$limit);
$j=0;
foreach($pages AS $page):
?>
<div class="jr-results jrResults jrModuleContainer jrReviewsModule">
<?php $i=0;
while(!empty($page)):
$i++; $j++; $review = array_shift($page); ?>
<?php
// Process link title
$listing_title = ($listing_title_chars && mb_strlen($review['Listing']['title'])>$listing_title_chars) ? $Text->truncate($review['Listing']['title'],$listing_title_chars) : $review['Listing']['title'];
$review_title = ($review_title_chars && mb_strlen($review['Review']['title'])>$review_title_chars) ? $Text->truncate($review['Review']['title'],$review_title_chars) : $review['Review']['title'];
$link_title = str_replace('{listing_title}',$listing_title,$link_title_format);
$link_title = str_replace('{review_title}',$review_title,$link_title);
// Create the thumbnail
$tn_show and $mainMediaThumb = $Media->thumb(Sanitize::getVar($review,'MainMedia'),array('listing'=>$review,'size'=>$tn_size,'mode'=>$tn_mode,'css_size'=>true));
?>
<?php $lastItem = ($i == $columns) ? ' jrLastItem' : ''; ?>
<div class="jrModuleItem<?php echo $lastItem; ?>" style="width: <?php echo $item_width; ?>%; padding-right: <?php echo $item_padding; ?>%;">
<?php if($show_numbers):?><div class="jrModuleItemNumber"><?php echo $j;?>.</div><?php endif;?>
<?php if($tn_show && $mainMediaThumb && $tn_position != 'bottom'):?>
<!-- Listing Thumbnail -->
<div class="jrModuleItemThumbnail">
<?php echo $Html->sefLink($mainMediaThumb,$review['Listing']['url']);?>
<?php // Uncomment line below to show reviewer avatar. You can comment or remove the thumbnail code above
// echo $Community->avatar($review);
?>
</div>
<?php endif;?>
<div class="jrModuleItemContent">
<!-- Listing Title -->
<div class="jrModuleItemTitle">
<?php echo $Html->sefLink($link_title,$review['Listing']['url']);?>
<?php if(Sanitize::getString($review['Listing'],'tag')):?>
<span class="jrComponentLabel jrStatusLabel jrBlue">
<?php echo Sanitize::getString($review['Listing'],'tag');?>
</span>
<?php endif;?>
</div>
<!-- Rating -->
<?php if ( $review['Criteria']['state'] == 1 ):?>
<div class="jrOverallRatings">
<?php if($review['Review']['editor'] == 1):?>
<?php
$rating_stars = $Rating->drawStars($review['Rating']['average_rating'], $this->Config->rating_scale, 'editor');
$rating_value = $Rating->round($review['Rating']['average_rating'],$this->Config->rating_scale);
?>
<div class="jrOverallEditor" title="<?php __t("Editor rating"); ?>">
<div class="jrRatingStars"><?php echo $rating_stars ?></div>
<span class="jrRatingValue"><?php echo $rating_value?></span>
</div>
<?php else:?>
<?php
$rating_stars = $Rating->drawStars($review['Rating']['average_rating'], $this->Config->rating_scale, 'user');
$rating_value = $Rating->round($review['Rating']['average_rating'],$this->Config->rating_scale);
?>
<div class="jrOverallUser" title="<?php __t("User rating"); ?>">
<div class="jrRatingStars"><?php echo $rating_stars ?></div>
<span class="jrRatingValue"><?php echo $rating_value?></span>
</div>
<?php endif;?>
</div>
<?php endif;?>
<!-- Reviewer name -->
<div class="jrModuleItemReviewer">
<span class="reviewer"><?php __t("Reviewed by");?> <?php echo $Community->screenName($review);?></span>
</div>
<?php if($fields): ?>
<!-- Custom Fields -->
<div class="jrModuleFields">
<?php
foreach ($fields as $field):
$field = trim($field);
$field_value = $CustomFields->field($field,$review);
?>
<?php if($field_value != ''):?>
<div class="jrModuleFieldDiv <?php echo lcfirst(Inflector::camelize($field)); ?>">
<span class="jrModuleFieldTitle"><?php echo $CustomFields->label($field, $review); ?>: </span>
<span class="jrModuleFieldValue"><?php echo $field_value; ?></span>
</div>
<?php endif;?>
<?php endforeach; ?>
</div>
<?php endif;?>
<?php if($show_comments && trim($review['Review']['comments'])!=''):?>
<!-- Review Comments -->
<div class="jrModuleItemInfo">
<?php
// Uncomment line below to show review title
// echo '<strong>' . $review['Review']['title'] . '</strong><br />';
?>
<span class="comments">"<?php echo $Text->truncateWords($review['Review']['comments'],$comments_words,'...');?>"</span>
</div>
<?php endif;?>
</div>
<?php if($tn_show && $mainMediaThumb && $tn_position == 'bottom'):?>
<!-- Listing Thumbnail -->
<div class="jrModuleItemThumbnail">
<?php echo $Html->sefLink($mainMediaThumb,$review['Listing']['url']);?>
<?php // Uncomment line below to show reviewer avatar. You can comment or remove the thumbnail code above
// echo $Community->avatar($review);
?>
</div>
<?php endif;?>
</div>
<?php /*end of row , start new row*/
if(!empty($page) && ($i == $columns || $total == $j)):?>
<div class="jrDivider"></div>
<?php $i=0; endif;?>
<?php endwhile;?>
</div>
<?php endforeach; /* new page ends here */?>
</div><?php /* end items root element */?>
Does any one have the slightest idea how i could turn this into a for loop that outputs a table?
The quickest path from A to B is to edit the attached code to render a table versus stacked divs.
* EDIT *
The answer to your comment isn't so simple as replace all of 'A' with 'B.' A div is a "self-contained" HTML element while a table is a grouping with syntax rules.
An HTML table is constructed like so:
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 - Column 1</td>
<td>Row 1 - Column 2</td>
</tr>
<tr>
<td>Row 2 - Column 1</td>
<td>Row 2 - Column 2</td>
</tr>
</tbody>
</table>
The foreach loop in your code should create a row through each iteration. Which means you need to render your table, thead and tbody tags outside of this looping code. Inside the loop, you render a new row each iteration, which requires an opening/closing tag for the row and an opening/closing for each column.
Hope this helps.
I have a table in MySQL with 5 rows (filename, location, type, author, date) and I would like to use PHP to print something like the following:
<div id="file">
(filename) - (author)<br>
(type) - (date)
</div>
I would like a new div to be created for every row in the table, is this possible?
<?php
while($row = mysql_fetch_assoc($result)){
echo '<div id="file">'.$row['filename'].' - a '.$row['author'].'<br>
'.$row['type'].' - '.$row['date'];
}
you need to iterate like so:
<?php $result = mysql_query('SELECT * FROM files;') ?>
<?php while($row = mysql_fetch_assoc($result)) : ?>
<div id="file">
<a href="<?php echo $row['location'] ?>">
<?php echo $row['filename'] ?>
</a>
- <?php echo $row['author'] ?>
<br>
<?php echo $row['type'] ?> - <?php echo $row['date'] ?>
</div>
<?php endwhile ?>