So on my project I have posts. And basically they include the post time and post content. Now here's my issue, I can only figure out how to retrieve one row instead of post content and post time. Here's my code
$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$posts[] = $row['post_content'];
}
And how I'm returning
<?php
foreach($posts as $post) {
$post;
?>
<div class="content">
<div class="post">
<h1 class="message">
<?php
echo $post;
?>
</h1>
<p class="time">4 minutes ago</p>
</div>
</div>
<?php
}
?>
I've tried
$posts = array();
$time = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$posts[] = $row['post_content'];
$time[] = $row['post_time'];
}
But that doesn't work. I've ran out of ideas. Any help would be great. Also if there is a cleaner way to do this, it would be nice knowing how. Thanks
You can use nested arrays:
$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$posts[] = array(
'post_content' => $row['post_content'],
'time' => $row['post_time']
);
}
Then your echo needs to reference $post['post_content'] and $post['time'].
Your're using $post = value, this will overwrite your value each time, try:
array_push($posts, $row['post_content']);
inside of your while loop
You could simply generate your HTML within the while loop. Otherwise, you might like to populate your posts array directly with PDOStatement::fetchAll -
$posts = $stmt->fetchAll();
and use it as you have been, e.g -
<?php foreach($posts as $post): ?>
<article>
<h1> <?php echo $post['title']; ?> </h1>
<p> <?php echo $post['content']; ?> </p>
</article>
<?php endforeach; ?>
Related
I have a PHP code that posts the articles I have made, but from Oldest to Newest and I need it to be Newest to Oldest, so the order is the issue
The inside of the "posts" row inside my database
This is the function I am using to put the posts in an array:
function getPublishedPosts() {
// use global $conn object in function
global $conn;
$sql = "SELECT * FROM posts WHERE published=true";
$result = mysqli_query($conn, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $posts;
}
And this is the visual part of the code:
<?php foreach ($posts as $post): ?>
<div class="post" style="margin-left: 0px;">
<img src="<?php echo BASE_URL . '/static/' . $post['image']; ?>" class="post_image" alt="">
<a href="single_post.php?post-slug=<?php echo $post['slug']; ?>">
<div class="post_info">
<h3><?php echo $post['title'] ?></h3>
<div class="post-body-div">
<?php echo html_entity_decode($post['body']); ?>
</div>
<div class="info">
<span><?php echo date("F j, Y ", strtotime($post["created_at"])); ?></span>
</div>
</div>
</a>
</div>
<?php endforeach ?>
just use SQL query to order by created_at.
replace your function like this.
function getPublishedPosts() {
// use global $conn object in function
global $conn;
$sql = "SELECT * FROM posts WHERE published=true order by created_at desc";
$result = mysqli_query($conn, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $posts;
}
You could just reverse the array holding your posts using array_reverse
<?php foreach (array_reverse($posts) as $post): ?>
http://docs.php.net/manual/da/function.array-reverse.php
(Better would be of course ordering the SQL using ORDER BY, but we need more information about the available database fields.)
I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help
This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
I'm trying to figure out how to get the current post ID from my main wp_query loop to work in the nested loop..
I've added my loops below with most HTML removed to make it cleaner to see.
I need to replace the "16" where it says "$currentID = 16;" in the nested loop with the actual current post ID from the main loop.
<?php $related_query = new WP_Query( 'post_type=post&posts_per_page=-1' ); ?>
<?php if( $related_query->have_posts() ): ?>
<?php while ( $related_query->have_posts() ) : $related_query->the_post(); ?>
<?php the_ID(); ?>
<?php the_time('F j, Y'); ?>
<?php the_category(); ?>
<?php echo get_edit_post_link(); ?>
<?php echo get_post_meta(get_the_ID(), 'cf_meta-desc', true); ?>
<?php echo get_post_meta(get_the_ID(), 'cf_xray', true); ?>
<?php the_tags(); ?>
<ul>
<h4>Recommended Articles</h4>
<?php
$related_cfs = get_post_meta( get_the_ID(), 'cf_related' );
foreach($related_cfs as $related_cf) {
echo '<li>';
echo '<span class="related-links__id">' .$related_cf. '</span>';
echo '<span class="related-links__title"><a target="_blank" href="' .get_permalink($related_cf). '">' .get_the_title($related_cf). '</a></span>';
echo '<span class="related-links__edit"><a target="_blank" href="' .get_edit_post_link($related_cf). '">edit</a></span>';
echo '</li>';
} ?>
</ul>
<?php global $post;$backup=$post; //saves main query data before calling nested query ?>
<!-- BEGIN NESTED LOOP -->
<?php $referral_query = new WP_Query( 'meta_key=cf_related&posts_per_page=-1' ); ?>
<ol>
<h4 class="referring-links__header">Linkbacks (<?php
$meta_key = 'cf_related';
$currentID = 16;
$sql = "SELECT count(DISTINCT pm.post_id)
FROM $wpdb->postmeta pm
JOIN $wpdb->posts p ON (p.ID = pm.post_id)
WHERE pm.meta_key = '$meta_key'
AND pm.meta_value = '$currentID'
";
$count = $wpdb->get_var($sql);
echo "$count";
?>)
</h4>
<?php while ( $referral_query->have_posts() ) : $referral_query->the_post(); ?>
<?php
$currentID = 16;
$arrayCFrelated = get_post_custom_values('cf_related');
if (in_array($currentID, $arrayCFrelated))
{ ?>
<li>
<?php the_ID(); ?>
<?php the_title(); ?>
<?php echo get_edit_post_link(); ?>
</li>
<?php } ?>
<?php endwhile; ?>
</ol>
<!-- END NESTED LOOP -->
<?php $post=$backup; //brings back main query data before called nested query ?>
<?php echo get_post_meta(get_the_ID(), 'cf_img-feature', true); ?>
<?php endwhile; ?>
<?php else: ?>
<p class="center">Nothing found.</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
The code you posted is very hard to read because it is all nested and distributed between opening and closing php tags.
First of all - You should consider to get familiar with functions and objects as an alternative to nest everything within the same loop. This will also help other developers who work with you to understand your code.
As for your problem. Try using other types of loops to get indices within the loop. For example:
for ($i1=0; $i1 < count($yourarray); $i1++) {
// ...
echo "index: $i1 <br />";
echo "value: {$yourarray[$i1]}";
}
or
foreach ($array AS $idx => $value) {
// ...
echo "index: $idx <br />";
echo "value: $value";
}
I know this question is old but I run into the same issue recently.
If you have a main loop and want to get the ID (or any other data) of the current post to be used inside of a nested wp_query then use the global $post object.
Using 'get_the_id()' inside of the nested wp_query will return the id of the current post in the nested wp_query and not the main query
Example:
$post_id = $post->ID;
i have a website structure as follow
<div id="title">
<h1> //call $title here after executing loop </h1>
</div>
<?php
...
while ($row = $result->fetch_assoc()) { $title = $row['title']; ?>
<h2> this is the <?php echo $title;?> </h2>
<?php } ?>
is there a way i could still use or call the $title variable on an html element on top of the while loop statement?
whenever i call it above the while loop i get errors like Undefined variable: id..
edit: change id into 'title' instead
PHP will read code line by line so variable can't be used before declaration.
Only one option is to move loop above your div, get html from loop inside variable and print it later.
I think that you've got only one row in that loop so use this code instead.
$row = $result->fetch_assoc();
$title = $row['title'];
echo '<h2> this is the '.$title.' </h2>';
If you're only retrieving a single row, you don't need the loop:
<?php
$row = $result->fetch_assoc();
$title = $row['title'];
?>
<div id="title">
<h1><?php echo $title; ?></h1>
</div>
So basicly what I'm trying to accomplish is that foreach row in mysql query it prints out the html with the data from that row. Here's what I have, it keeps giving me an error on my foreach.
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row=mysql_fetch_array($shots))
$data[]=$row;
foreach($shots as $data)
if (!empty($data)){
$id = $data["id"];
$shotby = $data["shot"];
$passby = $data["pass"];
$time = $data["time"];
?>
<div class="feedbody">
<div class="title"><?php echo $shotby; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $passby; ?</span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php
}
}
?>
Or something like that. Can anybody help point me in the right direction. I've been trying to find the answer.
EDIT: adding the error as requested.
Warning: Invalid argument supplied for foreach() in /home/content/93/7527593/html/fusionboard/includes/feed.php on line 7
First, if you want to access the data by name (instead of index), you need to include MYSQL_ASSOC as a second parameter to mysql_fetch_array, or use mysql_fetch_assoc.
Not really sure why you were copying the MySQL results to a second array just to loop through that later - you can loop through the results directly:
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row = mysql_fetch_assoc($shots)) { ?>
<div class="feedbody">
<div class="title"><?php echo $row["shot"]; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $row["pass"]; ?></span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php } ?>
Update after you posted the error message: the error from your original code was that you first went through and copied each result row into $data, but then in your foreach you tried to loop on $shots (again) and have it call each item $data.
What you probably wanted to do was have foreach ($data as $item) and then copy the properties from $item.
Something like this?
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row=mysql_fetch_assoc($shots))
{
$id = $row["id"];
$shotby = $row["shot"];
$passby = $row["pass"];
$time = $row["time"];
?>
<div class="feedbody">
<div class="title"><?php echo $shotby; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $passby; ?</span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php
}
?>
Perhaps you need another closing brace? (Another "}" at the end, I mean).
You saved your data in the $data variable, but your foreach uses the $shots variable.
Just change it to foreach($data as $something) and $something["id"] (for example) to retrieve a value
you are using one variable instead of another.
and many useless code.
while youneed only
<?php foreach($data as $row) { ?>
<div class="feedbody">
<div class="title"><?php echo $row['shotby'] ?></div>
<div class="feed-data">:
gets a pass from <span><?php echo $row['passby'] ?</span> and he takes a shot!
</div>
<img class="dot" src="images/dot.png" />
</div>
<?php } ?>