Unable to get a PHP array to display its contents in reverse - php

I've spent a lot of time looking at methods to do this and functions yet not been able to get the contents to display to screen in reverse.
I want to show the most recent entries in a blog at the top of the list. So here's what I have so far but the array doesn't seem to be reversing and neither is the while loop working that displays the elements that I want (I used print_r and var_dump just for debugging.
<body class="body">
<ul>
<?php
include 'config.php';
include 'opendb.php';
$sql = 'SELECT post_id AS "id", post_title AS "title", post_datetime AS "datetime" FROM posts WHERE post_id IS NOT NULL';
$res = mysqli_query($conn, $sql);
while (($post = $res->fetch_assoc())){
echo current($post);
}
array_reverse_keys($post);
foreach ($post as $value) {
print_r($value);
}
while ($post) {
?>
<li>
<?php
if (isset($post)) {
?>
<a href="#" data-id="<?php echo $post['id'] ?>">
<?php echo $post['title']?></a>
<?php
}
?>
</li>
<?php
}
?>
</ul>
<?php
$conn->close();
?>
</body>
</html>
The function being called reads:
<?php
function array_reverse_keys($ar){
return array_reverse(array_reverse($ar,true),false);
}
?>
Can anyone assist please?
Kind regards,
Mark

Your function is returning the new array, but you're not using the returned value when you call it. It should be:
$post = array_reverse_keys($post);

Change your sql add order by clause
eg:
$sql="SELECT post_id AS "id", post_title AS "title", post_datetime AS "datetime" FROM posts WHERE post_id IS NOT NULL order by id DESC";

Change this line
array_reverse_keys($post);
to
$post = array_reverse_keys($post);

Related

Open the Blog Posts by clicking on the Blog Categories

I have a blog page. I want that when a user Clicks on "All Posts", it should show all posts from Blog. And when someone clicks on a category like "Catering", it should show the posts from "Catering" category only.
Here is what i have did so far
<div class="blog-nav">
<ul class="nav">
<li><a>All Posts</a></li>
<?php
$SelectBlogcats = mysqli_query($con, "SELECT * FROM blog GROUP BY cat_blog");
while($row = mysqli_fetch_assoc($SelectBlogcats)){
$Cat_query = mysqli_query($con,"SELECT * FROM cat_blog WHERE
id=".$row['cat_blog']);
$main_cat = mysqli_fetch_assoc($Cat_query);
?>
<li><a><?php echo $main_cat['bcat_name'];?></a></li>
<?php } ?>
</ul>
</div>
Tested and working answer
<?php
$cat_id=0;
$condition="";
if(isset($_GET['cat'])){
$cat_id=$_GET['cat'];
$condition="where cat_blog=$cat_id";
}
$SelectBlogcats = mysqli_query($con, "SELECT * FROM blog GROUP BY cat_blog");
while($row = mysqli_fetch_assoc($SelectBlogcats)){
$Cat_query = mysqli_query($con,"SELECT * FROM cat_blog WHERE
id=".$row['cat_blog']);
$main_cat = mysqli_fetch_assoc($Cat_query);
?>
<li>
<h2><?php echo $main_cat['bcat_name'];?></h2>
</li>
<?php } ?>
Some semi-pseudo code which might help you accomplish your goals - wholly untested however.
The nested sql queries you have is not very efficient and it is highly likely that a simple join between the tables is what you really need.
Each hyperlink used to select a new / different category to display needs to set ( in this example ) a querystring parameter which can be used to filter records from the entire recordset.
<?php
/*
Hopefully a single query should suffice
joining the two tables rather than querying
separately.
Store the result of the query and use that to build
the nav menu and also display the content late
*/
$cat=!empty( $_GET['category'] ) ? $_GET['category'] : 'all';
# without seeing the schema this is a guess!
$sql='SELECT * FROM `blog` b
JOIN `cat_blog` cb on cb.`id`=b.`cat_blog`
GROUP BY b.`cat_blog`';
$res=$con->query( $sql );
$rs=$res->fetch_all( MYSQLI_ASSOC );
?>
With the data stored in an associative array you can proceed to generate the hyperlink menu where each link has a querystring variable set; ie: ?category=X
<div class="blog-nav">
<ul class="nav">
<li><a href='?category=all'>All Posts</a></li>
<?php
foreach( $rs as $row ){
$active = $cat==$row['bcat_name'] ? ' class="active"' : '';
printf( '
<li%2$s>
%1$s
</li>
',
$row['bcat_name'],
$active
);
}
?>
</ul>
</div>
The recordset can then be processed again to output the actual blog content paying attention to the variable $cat to dictate which records are to be displayed.
<!-- blog display - ALL records or the filtered subset -->
<div class="blog-content">
<?php
if( !empty( $rs )){
foreach( $rs as $row ){
// display only the filtered category or ALL records
if( $cat==$row['cat_name'] or $cat=='all' ){
/* output your blog content ..... */
}
}
}else{
echo 'There was an error fetching database records.';
}
$res->close();
?>
</div>

var_dump shows data but echo says Undefined index - At a loss

I've got two queries going on, one is working fine... Echos all the right column values. The second one shows all the data var_dump but keeps showing Undefined Index. I don't understand what I've done wrong.
I tried to make an array to define the index via the suggestion of a developer but that gave me zero results
$navpage = array();
$navpage['splash_id']='';
etc but that results in the empty space obviously... I don't know why this was the solution I was led to.
Error code says : Notice: Undefined index: splash_id in...
I know there are so many questions like this and most of them are talking about email forms they are working on, while I am just trying to output data from the database.
Here is my query file arts.php
<?php
require 'scripts/start.php';
$pages = $db->query("SELECT article_id, department, title, article_link, shortdesc, img_meta, live FROM content WHERE department='Arts' AND live='Yes'
")->fetchAll(PDO::FETCH_ASSOC);
$navpage = $db->query("SELECT splash_id, page, live, big_message, img1, text1, link1, expdate FROM splash WHERE page='arts' AND live='Yes'
")->fetchAll(PDO::FETCH_ASSOC);
require VIEW_ROOT . '/artpages.php';
?>
The page where I echo things like column - text1
<?php require VIEW_ROOT . '/department/arts_header.php';
?>
<div id="major">
<div id="so" class="mainimage">
<div class="mainimage"><img src="cms_img/header/<?php echo $navpage['img1']?>" class="splashimage"></div>
</div>
<div id="contentbox">
<div id="middle"><div id="articleheadline" class="titlefont"><?php echo $navpage['text1']?></div>
<?php if (empty($pages)): ?>
<p class="textfont">Sorry, there are no articles on this page.</p>
<?php else: ?>
<?php foreach($pages as $page): ?>
<div class="article_container">
<div class="article_promo"><img src="cms_img/<?php echo escape($page['img_meta']) ?>"class="promofit"></div>
<div class="article_title"><span class="article_title_font"><?php echo $page['title']?></span></div>
<div class="article_desc"><span class="article_desc_font"><?php echo $page['shortdesc']?></span></div>
</div><?php endforeach; ?>
<?php endif; ?>
</div></div></div></div>
<?php
require VIEW_ROOT . '/templates/footer.php';
?>
I expect echos of $navpage to fill in like $page does.
Fetch all get a multiple array result so you need to use foreach loop like you did in $pages or use the following code below to fetch only a single array.
$dbh = new PDO("SELECT article_id, department, title, article_link, shortdesc, img_meta, live FROM content WHERE department='Arts' AND live='Yes'");
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1");
$stmt->execute();
$navpage= $stmt->fetch();
Because you use ->fetchAll(PDO::FETCH_ASSOC). Its return array of item navpage
So you must to code $navpage[0]['img1'] and $navpage[0]['text1']
Notice check !empty($navpage) before use $navpage[0]

Php while codes show just 1 row

I'm using these codes.
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
echo "$fake";
}
When i use echo"$fake"; I can see all of my rows. But when I use <?php echo "$fake" ?> , It shows just 1 row for me.
I want to all of my rows while I'm using <?php echo "$fake" ?>.
Beacuse The echo"$fake"; in with in a loop it will echo at every iteration thats why you can see all your rows but <?php echo"$fake"; ?> executed when the loop is done so only the last row will be echoed;
You should seperate your logic like
<?php
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
?>
<?php
echo $fake;
}

PDO mysql and PHP: Undefined index and Trying to get property of non-object

Anyone please help me fix my php code here.
Im working with php and PDO and I have been switching codes around but nothing works. Any help will be appreciated.
Here is the code for my index page:
<?php
require_once 'init.php';
$supportQuery = $conn -> query("
SELECT id, title, content
FROM table");
while ($row=$supportQuery ->fetchObjecy()) {
$support[]=$row;
}
?>
<?php if(!empty($support)): ?>
<?php foreach($support as $supp): ?>
<a href="page.php?id=<?php echo $supp->id; ?>&title=<?php echo $supp->title; ?>">
<?php echo $supp->title; ?></a>
<?php endforeach; ?>
<?php else: ?>
No items found.
<?php endif; ?>
This code works the way I like it to work but when I run code and click the link, that is where I am getting errors.
Here is my php code for page.php:
<?php
require_once 'init.php';
$articleQuery = $conn -> prepare("
SELECT id, title, content
FROM table WHERE id='$id' and title='$title'");
while ($row=$articleQuery ->fetchObject()) {
$support[]=$row;
}
$articleQuery->execute();
?>
<?php if(!$_SESSION($support)): ?>
<?php echo $support->id; ?>
<?php echo $support->title; ?><br/>
<?php echo $support->content; ?>
<?php else: ?>
<p>Are you inventing titles? Sorry but this page doesnt exist nowhere.</p>
<?php endif; ?>
I need your help please. I am getting the following error messages:
Notice: Undefined index: title and id in /page.php
Notice: Undefined variable: support in /page.php
Notice: Trying to get property of non-object in /page.php
♡nbgmalimit
Ok, to start...
1) In the 2nd code block, you need to execute the statement BEFORE trying to fetch the results.
2) You should be binding the values $id and $title prior to executing to avoid sql injection.
Look at the examples in the manual to see how to do both of these...
http://php.net/manual/en/pdostatement.execute.php
3) You're fetching the row as an object and adding the resulting object as a value in the $support ARRAY.
4) Assuming the id and title are unique, you do not need to loop it and add it to an array, as you should only get 1 row returned. Just use fetch. Using PDO::FETCH_ASSOC for the fetch style will return an array. Using PDO::FETCH_OBJ for the fetch style will return an object.
http://php.net/manual/en/pdostatement.fetch.php
Try something like this...
$row = null;
$stmt = $conn->prepare("SELECT id, title, content FROM table WHERE id = :id and title = :title");
$stmt->bindParam( ":id", $id, PDO::PARAM_INT );
$stmt->bindParam( ":title", $title, PDO::PARAM_STR );
$result = $stmt->execute();
if ($result) {
$row = $stmt->fetch(PDO::FETCH_OBJ);
} else {
// handle error
}
?>
<?php if(!empty($row)): ?>
<?php echo $row->id; ?>
<?php echo $row->title; ?><br/>
<?php echo $row->content; ?>
<?php else: ?>
<p>Are you inventing titles? Sorry but this page doesnt exist nowhere.</p>
<?php endif; ?>

Codeigniter/PHP - Displaying results of two related queries in same view, blog app

I am new to both PHP and the Codeigniter(v2.0) framework. Hoping you can help me find my way through my first webapp. Details below, and thank you in advance!
Goal/Issue Summary: I would like to display within my view all blog_Comments that are attached to each paticular blog_Post.
Details: My blog_Posts table contains all original blog posts [id(int), title, entry, author (all varchar), and date(timestamp)]. My blog_Comments table[id(int), entry_id(int), author, comment(varchar)] contains all comments; they are associated with the original blog_Post via the *entry_id* attribute.
Controller:
$query1 = $this->blog_model->get_posts();
$query2 = $this->blog_model->get_comments();
$data = array();
$data['posts'] = $query1;
$data['comments'] = $query2;
Model:
function get_posts() {
$query = this->db->get('blog_Posts');
return $query->result;
}
function get_comments() {
$query = this->db->get('blog_Comments');
return $query->result;}
View:
<?php if(isset($posts)) : foreach($posts as $posts=>$row) : ?>
<?php $row->title; ?>
<?php $row->author; ?>
<?php $row->entry; ?>
<?php foreach($comments as $comments=>$com) : ?>
<?php if($com->entry_id == $row->id) : ?>
<p>author: <?php echo $com->author; ?></p>
<p>comment: <?php echo $com->comment; ?></p>
<?php endif; ?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php else : ?> <p>no blog_Posts found</p>
<?php endif; ?>
Edit/Update:
My attempt to display the comments is pasted into the view code block above, I've also listed the two issues it is giving me. Right now I have 2 sample original blog posts, and comments associated with each.
Issues:
the first blog entry (first time through the loop) it is displaying ALL comments, including those associated with other entry_id s.
The second blog entry (second time through loop), it throws the following error: "Invalid argument supplied for foreach()", and points to the line in my view containing the foreach for $comments.
In short, I'm trying to loo through only those comments with the entry_id that matches the original posts "id."
Thanks again for your assistance and time.
-AJ
Well since you do not need to display all comments at once, you could just alter your get_comments function like below to return comments for each post and of course display them in your way, order by date created, last entry etc:
So for the model part:
function get_comments($post_id){
$query = $this->db->query("select * from `blog_Comments` where `entry_id` = $post_id ORDER BY `created_on` DESC");
if($query->num_rows() != 0){
return $query->result();
}else{
return false;
}
}
And in your view file:
foreach($posts as $row){
echo 'Title: ' . $row->title .
'Author: ' . $row->author .
'Entry:' . $row->entry;
$comments = $this->blog_model->get_comments($row->id);
if(!$comments){
echo 'No comments';
}else{
foreach($comments as $com){
echo $com->comments . '<br/>' . $com->user . '<br/>' . etc etc
}
}
}
I'm too lazy to test, but i think you are trying to use $row, but you are outside the foreach where its defined. you introduce $row here
<?php if(isset($posts)) : foreach($posts as $posts=>$row) : ?>
and then you close the foreach -- so $row is no longer available down here:
<?php if($com->entry_id == $row->id); ?>
so yeah. but really you should be doing as much logic and checking as you can in the controller and model. verify your data objects - like Posts - THEN the controller determines the correct view. so then if there aren't any posts to show -- you dont have messy 'what if there are no posts' conditionals in your view. you just call the no posts view file.

Categories