PHP Html in while loop - php

I have two html / css content. One of them floating left, the other one floating right.
I wanna pull data from my database, then putting them in a order. Left, right, left, right.
$services = pullservices();
while ($service = mysqli_fetch_object($services)){
for ($i=1; $i<=mysqli_num_rows($services); $i++) {
if ($i % 2 == 0): ?>
Left HTML Content
<?php else: ?>
Right HTML Content
<?php
endif;
}
}
?>
I have 6 items on db. But that code keeps looping one data for 6 times and it doing that for all the data on db.
That is the pullservices function.
function pullservices()
{
global $connect;
$products_query_string = "SELECT
id,
title_tr AS title,
text_tr,
short_text_tr,
image,
icon
FROM services WHERE status = 1 ORDER BY ordering , title_tr";
$products_query_run = mysqli_query($connect, $products_query_string);
return $products_query_run;

You can do this simply by using a flag.
(pseudo code):
$services = pullservices();
$flag=0;
while ($service = mysqli_fetch_object($services)){
if ($flag==0): ?>
Left HTML Content
<?php $flag=1; ?>
<?php else: ?>
Right HTML Content
<?php $flag=0; ?>
<?php
endif;
}
?>

One way you might be able to do this would be to split the data from the recordset and call it later in the html like this
$services = pullservices();
$i=0;
$data=array(
'left' =>array(),
'right' =>array()
);
while( $rs = mysqli_fetch_object( $services ) ){
$key = $i % 2 == 0 ? 'right' : 'left';
/* add the real data rather than placeholder data */
$data[ $key ][]=sprintf('%s HTML Content %d', ucfirst( $key ), $i );
$i++;
}
<div id='left'>
<?php
echo implode( PHP_EOL, $data['left'] );
?>
</div>
<div id='right'>
<?php
echo implode( PHP_EOL, $data['right'] );
?>
</div>

Related

Wrapping in while loop is creating extra div

I have this code that's creating an extra empty div when there are extactly 3, 6, 9, etc items.
<?php
$i = 1;
echo '<div class="three-item-wrapper">';
if( have_rows('upcoming_stops_asia') ): while ( have_rows('upcoming_stops_asia') ) : the_row();
?>
<div class="item">Content</div>
<?php
if($i % 3 == 0) {echo '</div><div class="three-item-wrapper">';}
$i++; endif; endwhile; endif;
echo '</div>';
?>
I'm not sure how to fix it.
You are ending the current div and starting a new one when you get to a multiple of 3. If there are no more after that, then the div will of course be empty. One solution would be to accumulate the results and output them in a div only as required:
<?php
if( have_rows('upcoming_stops_asia') ) {
$results = [];
while ( have_rows('upcoming_stops_asia') ) {
the_row();
// Add to the collection of results
$results[] = '<div class="item">Content</div>';
if( count($results) == 3 ) {
// Output three results and reset
echo '<div class="three-item-wrapper">' . implode($results) . '</div>';
$results = [];
}
}
// Output any additional results; no div generated if there aren't any
if( !empty(results) ){
echo '<div class="three-item-wrapper">' . implode($results) . '</div>';
}
}
?>

show div tag in php statement

I am now working on a WordPress theme base with the Advanced Custom Fields plugin, And I want to show a <div> tag when the if statement is true. Here is my code:
<?php
$rows = get_field('classification');
$sort = get_sub_field('sort');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++)?>
<?php if ( $i==1 || $i%5==0) { ?>
<div class="bor"></div>
<h3 style="text-align:center">
<?php echo $sort; ?>
<a id="browser"></a></h3>
<div class="bor"></div>
<?php } ?>
or something like that
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++)?>
<?php if ( $i==1 || $i%5==0) { ?>
echo '<div class="bor"></div>';
echo '<h3 style="text-align:center">';
<?php echo $fenlei; ?>
echo '<a id="browser"></a></h3>';
<div class="bor"></div>
<?php } ?>
But the content of the div tag doesn't show.
Any reply is appreciated!Thank you very much.
some of your echo statement are out php tags. use this:
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++){
if ( $i==1 || $i%5==0) {
echo "<div class='bor'></div>
<h3 style='text-align:center'>".$fenlei."
<a id='browser'></a></h3>
<div class='bor'></div>";
}
}
?>
If you wanted to show the html in php, i suggest you use the below code.
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for($i = 1; $i <= $row_count; $i++){
if ( $i==1 || $i%5==0) {
echo '>div class="bor"<>/div<';
echo '>h3 style="text-align:center"<';
echo $fenlei;
echo '>a id="browser"<>/a<>/h3<';
echo '>div class="bor"<>/div<';
}
}
?>
I'm guessing you're using an ACF Pro Repeater field. in this case you need to use the_row() which will set the sub-field's correct content. look at this edited example from the Docs:
<?php
// check if the repeater field has rows of data
if( have_rows('repeater_field_name') ):
// loop through the rows of data
while ( have_rows('repeater_field_name') ) : the_row();
// display a sub field value
the_sub_field('sub_field_name');
endwhile;
endif;
?>
so, I think your code should look more like:
<?php
if(have_rows('classification')):
while (have_rows('classification') ) : the_row();
// Your Code...
endwhile;
endif;
?>
And, I've learned recently you need to count the rows outside the while loop. othewise it won't catch the rows amount.

PHP looping over object manipulate output based on object length

I have a PHP object that I am looping over, I know 2 things are definate with this object, I will never need to loop more than 12 times (1-12) and I will also always have to loop at least once.
My problem comes when the object is longer than 6 items, as if it is longer than 6 items I need to split the results into 2 <ol> and for the live of me I cannot figure out a nice way to do this?
Here is my attempt,
<?php $count = 1; ?>
<?php if(is_object($active_projects)) : ?>
<div class="col_1">
<?php if($count < 2) : ?>
<strong>Active projects</strong> View All
<?php endif; ?>
<ol <?php echo ($count > 1 ? " class='no-header'" : ""); ?>>
<?php foreach($active_projects as $project) : ?>
<li><?php echo $project->project_name; ?></li>
<?php $count ++; ?>
<?php endforeach; ?>
</ol>
</div>
<?php endif; ?>
Now my attempt displays all the results in one list, how can if there are more than 6 items in the object, split the loop in 2 so that I output 2 <div class="col_1"> with a list of 6 items in each?
Try this:
<?php
//create an object with 12 items
$obj = new stdClass();
for($i = 1; $i <= 12; $i++)
{
$project = "project_$i";
$obj->{$project} = new stdClass();
$obj->{$project}->name = "Project $i";
}
function wrapInLi($projectName)
{
return "<li>$projectName</li>\n";
}
function wrapInOl($arrayOfLi)
{
$returnString = "<ol>\n";
foreach ($arrayOfLi as $li)
{
$returnString .= $li;
}
return $returnString . "</ol>\n";
}
/*
* The classname is adjustable, just in case
*/
function wrapInDiv($ol, $class)
{
return "<div class='$class'>\n$ol</div>\n";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$arrayOfLi = array();
foreach($obj as $project)
{
//fill an array with list-items
$arrayOfLi[] = wrapInLi($project->name);
//six list-items? wrap it
if(count($arrayOfLi) === 6)
{
//wrap in unordered list
$ol = wrapInOl($arrayOfLi);
//wrap in div and echo
echo wrapInDiv($ol, 'col_1');
//reset array
$arrayOfLi = array();
}
}
?>
</body>
</html>

Incorporating extra loop into random selection?

I have the code below that is selecting a random set of questions from Wordpress.
<?php
$rows = get_field('step_by_step_test');
$row_count = count($rows);
$rand_rows = array();
$questions = get_field('select_number_of_questions');
for ($i = 0; $i < min($row_count, $questions); $i++) {
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['question'];
}
?>
I want to incorporate a bit of extra code (below), how can I make sure it's selecting the same random question?
<?php if(get_sub_field('answer_options')): ?>
<?php while(has_sub_field('answer_options')): ?>
<?php echo the_sub_field('answer'); ?>
<?php endwhile; ?>
<?php endif; ?>
Why dont you change your approach slightly?
<?php
$rows = get_field('step_by_step_test'); // Get the test
$question_count = get_field('select_number_of_questions'); // Get the number of questions
$rows = shuffle($rows); // Randomize your questions
$rows = array_slice($rows, $question_count); // Now set the array to only contain the number of questions you wanted
foreach ($rows as $row) {
echo $row['question']; // Show the question
if(get_sub_field('answer_options', $row['id'])) {
while(has_sub_field('answer_options', $row['id'])) {
echo the_sub_field('answer');
}
}
}
?>
I made the assumption that you can alter "get_sub_field" to include the ID of the question, so you can then include the ID in your "where" field of "answer_options". This will allow you to link the question.
I think that what you need is to set up the whole thing in a loop. query by custom field
Or you could store the ids of the questions you got above, an then, below, query for the answers for those specific posts.
Here's how I randomized my WordPress slider using the Advanced Custom Fields plugin + Royal Slider with a modified version of TheSwiftExchange's code above
<div id="full-width-slider" class="royalSlider heroSlider rsMinW">
<?php
/*
* Slider Repeater field shuffled
* http://stackoverflow.com/questions/12563116/incorporating-extra-loop-into-random-selection
*/
$rows = get_field('slider');
// For Debugging:
// echo "<pre>";
// var_dump($rows);
// echo "</pre>";
$quotes = get_field('slide_text'); // Get the number of images
shuffle($rows); // Randomize your slides
foreach ($rows as $row) {
$slideImageID = $row['slide_image'];
$slideImage = wp_get_attachment_image_src( $slideImageID, 'full' );
$slideText = $row['slide_text'];
?>
<div class="rsContent">
<div class="royalCaption">
<div class="royalCaptionInner">
<div class="infoBlock">
<?php if(!empty($slideText)) {
echo $slideText;
}; ?>
</div>
</div>
</div>
<img src="<?php echo $slideImage[0]; ?>" class="" />
</div><!-- /.rsContent -->
<?php } // end foreach ?>
</div><!-- /slider-wrap -->

Codeigniter table Join then Display Tags Problem

I have a problem that concerns blog posts and displaying the tag words from another table.
I seem to be able to pull the info out of the tables fine, however when I try to display the posts and the tags, I get one tag per post. In other words if I have 7 tags for a post, I get 7 iteration's of that post each with one tag instead of 1 post with 7 tags.
My Controller ( do have a question about the $this->db->get(posts, tags) is that correct
$this->db->order_by('posts.id', 'DESC');
$where = "publish";
$this->db->where('status', $where);
$this->db->join('tags', 'tags.post_id = posts.id');
$this->db->limit('7');
$query = $this->db->get('posts', 'tags');
if($query->result())
$data = array();
{
$data['blog'] = $query->result();
}
$data['title'] = 'LemonRose';
$data['content'] = 'home/home_content';
$this->load->view('template1', $data);
The view.
$limit = 5; // how many posts should we show in full?
$i = 1; // count
foreach ($blog as $row):
$permalink = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
$url = CompressURL ("$permalink");
$description = $row->title . $row->post;
$twittermsg = substr($description, 0, 110);
$twittermsg .= "...more " . $url;
if ($i < $limit) // we are under our limit
{ ?>
<div class="titlebox">
<div class="title"><? echo ucwords($row->title); ?></div>
<span><? echo $row->date, nbs(10), $row->author; ?></span>
</div>
<div class="clear"></div>
<? $str = str_word_count($row->post, 0);
if ($str >= 500) {
$row->post = html_entity_decode($row->post);
$row->post = $this->typography->auto_typography($row->post); // display?>
<div class="split"> <? echo $row->post = word_limiter($row->post, 480); ?>
<div class="tags"><? echo $row->tag; ?></div>*** These 3 lines seem to be where I am confused and getting the wrong display
<p><h3>More <?php echo anchor("main/blog_view/$row->id", ucwords($row->title)); ?> </h3></p>
<p>Trackback URL: <? echo base_url() . "trackbacks/track/$row->id"; ?></p>
<!-- tweet me -->
<?echo anchor("http://twitter.com/home?status=$twittermsg", 'Tweet'); ?>
This is my first attempt with join and I have very little experience getting the display with implode, if that is the right way to go.
Thank you in advance.
Try
<div class="tags"><? echo implode(', ', $row->tag); ?></div>
and remove the 2 rows before this one.

Categories