Show posts belong to any category in php

hi mate,

i am just start coding with my PHP, i have to know about populate (fetch) content from database anyway so you no need to worry about this section :slight_smile:

today when i am trying to implement my new web task that my use can select any post category and i have to done with this task but there is one thing getting wrong :frowning:

first of all, here is sample of my URL to get list of post based on category that my user clicked:

http://localhost/cat.php?id=1

so this URL would fetch all content (post title, post author, post content, cat label, etc) but when i enter non exist cat id it will show show error like invalid argument supplied for foreach.

what should i do when my user want to get non exists cat_id without any php error instead show a 404 page error :x

You should work out first what you want to do if a cat has not been chosen:

Show all posts?
Show nothing, just a warning?

Likewise, if the cat id returns no records (presumably this should not happen, but could).

Show all posts?
Show nothing, just a warning?

A conditional check can be done like this.



// use (int) to typecast the incoming cat variable to an integer
// if it is not able to cast it as an integer, it will return 0
// so only go on with the action 
// IF id is set AND id is recognised as an integer greater than 0

if( isset($_GET['id'] && (int)$_GET['id'] > 0){

// now an integer has been submitted, but you will still have to work out 
// whether there are any matching records in your db
$sql = "select things FROM mytable where cat =" . $_GET['id'];

}else{

// now do your default action
// maybe show all things?
$sql = "select things FROM mytable";

}

// now action your sql statement.

Remove the comments. This could be run through PDO or Mysqli or Mysql functions, but I hope you get the general idea.

ough my God, it’s really should work for me

thanks mate, you save my lot of time when i can’t to do it.

hi mate,

i want to ask something else, i have done with this but i didn’t make sure any security issues. so, just forget about that for while:

(isset($_GET['id']) ? $catId = $_GET['id'] : '');
    
    require_once 'inc/database.php';
    
    // Get all post from database
    $getPosts = "SELECT posts.*, posts_categories.*, categories.*
                 FROM (posts
                 INNER JOIN posts_categories
                       ON posts.post_id = posts_categories.postid)
                 INNER JOIN categories
                       ON posts_categories.catid = categories.cat_id
                 WHERE categories.cat_id = '$catId'";
    $nowPosts = $db->query($getPosts);
    
    if (!$nowPosts)
    {
        $title = 'Please try again later!';
        echo "<p class=\\"dbError\\">This category could not display. Please try again later.</p>";
    }
    else
    {
        if ($nowPosts->num_rows == 0)
        {
            $title = '404, Page Not Found!'; 

            // I will set $posts[] array manually in below like this
            /*
            $posts = array ( 
                     array (
                        'title' => '404, Page Not Found!',
                        'post_id' => '',
                        'post_title' => '404, Page Not Found!',
                        'post_createon' => '',
                        'post_content' => 'There is no any content in this category. 
                                           Please select another category.',
                         
                     ));
           */

        }
        else
        {
            while ($post = $nowPosts->fetch_assoc())
            {
                $title = $post['cat_label'];
             
                // here, i sent the content from database to $posts[] array
                $posts[] = $post;
            }
        }
    }

ok, according to my comment at the above code. i have sent all content that fetched from database (mysql) to $posts array. so i do this code in html template:

<?php

foreach ($posts as $post): ?>
                <h1>
                    <a href="post.php?id=<?php echo $post['post_id']; ?>" 
                       title="<?php echo $post['post_title']; ?>">                    
                    <?php echo $post['post_title']; ?>
                    </a>
                </h1>
                <p><em>Created Date: <?php echo $post['post_createon']; ?></em></p>
                <p><?php echo $post['post_content']; ?></p>
                <?php endforeach;
?>

based on the above code, i must have some content in $posts array but when i have no any content in that category that mean no any content in $posts i will get error like this:


Notice:  Undefined variable: posts in /var/www/site/cat.php on line 117

Warning:  Invalid argument supplied for foreach() in /var/www/site/cat.php on line 117

so i think i can add any value in $posts array manually like first code in above that I’ve comment them. but, it’s still make me disturbed cause it will make the title clickable and will go to this url:

http://localhost/site/post.php?id=

you can see that this title will redirect us to post.php page with no any [id] value :frowning:

sorry for my bad english and explanation, but you can read my full code in attachment :slight_smile: