Create categories in blog using PHP and MYSQL | Part 5


Create categories in blog using PHP

We are createing a blog CMS from the first “ how to create a blog from beginning in PHP" tutorial. In this PHP tutorial, we will create the categories with blog posts. It will help you to link many blog posts in one category. Every blog CMS should have a category feature. We will create blog categories using PHP and MYSQL database.
Let’s create database tables for categories.


Create a table –
Table Name – techno_category

Create MYSQL table for categories in PHP blog


In the table above, we will insert the Category Id, category name(Title of category) and category Slug. The category slug will be used for SEO friendly URL. The category Id should be auto-increment.


Now, create another table –
Table name - techno_cat_links

Make categories in blog CMS using PHP

After adding the blog category, the blog categories also have to be displayed. Let us display the blog category.

Complete PHP code for blog categories


admin/blog-categories.php


<?php
//include config
require_once('../includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }

//show message from add / edit page
if(isset($_GET['delcat'])){ 

    $stmt = $db->prepare('DELETE FROM techno_category WHERE categoryId = :categoryId') ;
    $stmt->execute(array(':categoryId' => $_GET['delcat']));

    header('Location: categories.php?action=deleted');
    exit;
} 

?>
<?php include("head.php");  ?>
  Categories- Techno Smarter Blog
  
  <?php include("header.php");  ?>

<?php //show message from add / edit page if(isset($_GET['action'])){ echo '

Category '.$_GET['action'].'.

'; } ?> <table> <tr> <th>Title</th> <th>Operation</th> </tr> <?php try { $stmt = $db->query('SELECT categoryId, categoryName, categorySlug FROM techno_category ORDER BY categoryName DESC'); while($row = $stmt->fetch()){ echo '<tr>'; echo '<td>'.$row['categoryName'].'</td>'; ?> <td> </td> <?php echo '</tr>'; } } catch(PDOException $e) { echo $e->getMessage(); } ?> </table>

<?php include("sidebar.php"); ?> <?php include("footer.php"); ?>

In the code lines above, we added two buttons for delete and edit operation.

Along with creating a blog category table, blog posts also have to be linked in the blog category. The category ID and blog post ID will be stored in the table above. By joining two tables, blog posts can be displayed in the blog category.

Let's now create a form to insert (create blog category) a blog category in the admin panel by which the blog category can be inserted easily. Inserting the blog category is very easy, all of them have learned in the past tutorials how to insert data in the database. Insert the category using PHP and MYSQL.


Complete PHP code for Add Blog Category -


admin/add-blog-category.php

 <?php 
require_once('../includes/config.php');


if(!$user->is_logged_in()){ header('Location: login.php'); }
?>
<?php include("head.php");  ?>
    Add New Category- Techno Smarter Blog
    <?php include("header.php");  ?>

Add Category

<?php //if form has been submitted process it if(isset($_POST['submit'])){ $_POST = array_map( 'stripslashes', $_POST ); //collect form data extract($_POST); //very basic validation if($categoryName ==''){ $error[] = 'Please enter the Category.'; } if(!isset($error)){ try { $categorySlug = slug($categoryName); //insert into database $stmt = $db->prepare('INSERT INTO techno_category (categoryName,categorySlug) VALUES (:categoryName, :categorySlug)') ; $stmt->execute(array( ':categoryName' => $categoryName, ':categorySlug' => $categorySlug )); //redirect to index page header('Location: blog-categories.php?action=added'); exit; } catch(PDOException $e) { echo $e->getMessage(); } } } //check for any errors if(isset($error)){ foreach($error as $error){ echo '

'.$error.'

'; } } ?>


<input type='text' name='categoryName' value='<?php if(isset($error)){ echo $_POST['categoryName'];}?>'>

<?php include("sidebar.php"); ?> <?php include("footer.php"); ?>


Now we will learn how to edit the category, how to blog category can be edited. Editing the blog category is the same as editing the blog post in which the update query is used.


admin/edit-blog-category.php

    $categorySlug = slug($CategoryName);

                //insert into database
                $stmt = $db->prepare('UPDATE techno_category SET CategoryName = :CategoryName, categorySlug = :categorySlug WHERE categoryId = :categoryId') ;
                $stmt->execute(array(
                    ':CategoryName' => $CategoryName,
                    ':categorySlug' => $categorySlug,
                    ':categoryId' => $categoryId
                ));

In the code above, you can see the slug() function is used to convert the category title to the slug. We created slug() function in functions.php file . In the PHP code above, we are using the update query to update the category fields. We discussed update operation in the first PHP blog part.


Complete PHP code for Edit blog category –


admin/edit-blog-category.php

 
<?php //include connection file 
require_once('../includes/config.php');


if(!$user->is_logged_in()){ header('Location: login.php'); }
?>

<?php include("head.php");  ?>
    EDIT Category- Techno Smarter Blog
    <?php include("header.php");  ?>

Edit Category-Techno Smarter

<?php //if form has been submitted process it if(isset($_POST['submit'])){ $_POST = array_map( 'stripslashes', $_POST ); //collect form data extract($_POST); //very basic validation if($categoryId ==''){ $error[] = 'Invalid id.'; } if($CategoryName ==''){ $error[] = 'Please enter the Category Title .'; } if(!isset($error)){ try { $categorySlug = slug($CategoryName); //insert into database $stmt = $db->prepare('UPDATE techno_category SET CategoryName = :CategoryName, categorySlug = :categorySlug WHERE categoryId = :categoryId') ; $stmt->execute(array( ':CategoryName' => $CategoryName, ':categorySlug' => $categorySlug, ':categoryId' => $categoryId )); //redirect to categories page header('Location: blog-categories.php?action=updated'); exit; } catch(PDOException $e) { echo $e->getMessage(); } } } ?> <?php //check for any errors if(isset($error)){ foreach($error as $error){ echo $error.'
'; } } try { $stmt = $db->prepare('SELECT categoryId, CategoryName FROM techno_category WHERE categoryId = :categoryId') ; $stmt->execute(array(':categoryId' => $_GET['id'])); $row = $stmt->fetch(); } catch(PDOException $e) { echo $e->getMessage(); } ?>
<input type='hidden' name='categoryId' value='<?php echo $row['categoryId'];?>'>


<input type='text' name='CategoryName' value='<?php echo $row['CategoryName'];?>'>

<?php include("sidebar.php"); ?> <?php include("footer.php"); ?>


Now, you can create the blog category and edit the blog category.
Let's link the blog category to the blog article.


When the article is written in the blog, after that it is linked to the category, similarly, we will insert the blog category by fetching and linking it to the id of the blog article. We will insert linked category id and article id in another table.
Let's understand the PHP code.


admin/add-blog-article.php


Add the code below MYSQL insert query at line 76 (hint – above the header() function and below the add category comment)

 $articleId = $db->lastInsertId();
if(is_array($categoryId)){
    foreach($_POST['categoryId'] as $categoryId){
        $stmt = $db->prepare('INSERT INTO techno_cat_links (articleId,categoryId)VALUES(:articleId,:categoryId)');
        $stmt->execute(array(
            ':articleId' => $articleId,
            ':categoryId' => $categoryId
        ));
    }
}
 

In the PHP code above , we are inserting the articleId with categoryId . It will help to fetch the related post on category page.
Now, fetch and display the blog category in the HTML form.
Add the code below the Long Description(Body Content) text area.

 

Categories <?php $checked = null; $stmt2 = $db->query('SELECT categoryId, categoryName FROM techno_category ORDER BY categoryName'); while($row2 = $stmt2->fetch()){ if(isset($_POST['categoryId'])){ if(in_array($row2['categoryId'], $_POST['categoryId'])){ $checked="checked='checked'"; }else{ } } echo "<input type='checkbox' name='categoryId[]' value='".$row2['categoryId']."' $checked> ".$row2['categoryName']."<br />"; } ?>

In the code above , we are adding checkbox for categories . The checkbox will help to link one or more category with the blog post .
We can link one blog post to one or more than one category at a time.
This feature makes it better.

The update operation is the most important part of the blog. Now, we will create an update operation for the blog category. We will able to link or unlink a post to the blog category.


admin/edit-blog-article.php


Add the PHP code below the MYSQL update query at line 70 ( Hint – above the header() function)

  $stmt = $db->prepare('DELETE FROM techno_cat_links WHERE articleId = :articleId');
$stmt->execute(array(':articleId' => $articleId));

if(is_array($categoryId)){
    foreach($_POST['categoryId'] as $categoryId){
        $stmt = $db->prepare('INSERT INTO techno_cat_links (articleId,categoryId)VALUES(:articleId,:categoryId)');
        $stmt->execute(array(
            ':articleId' => $articleId,
            ':categoryId' => $categoryId
        ));
    }
}

In the above code, you can see that the article ID has been deleted. If you uncheck the checkbox and update, then the blog post link should be deleted and if it does not change any, then the same category ID and post id should be insert.
Now , add the checkbox in the HTML form . Add the checkbox code after the long description (Body Content) textarea .

Categories <?php $checked = null; $stmt2 = $db->query('SELECT categoryId, categoryName FROM techno_category ORDER BY categoryName'); while($row2 = $stmt2->fetch()){ $stmt3 = $db->prepare('SELECT categoryId FROM techno_cat_links WHERE categoryId = :categoryId AND articleId = :articleId') ; $stmt3->execute(array(':categoryId' => $row2['categoryId'], ':articleId' => $row['articleId'])); $row3 = $stmt3->fetch(); if($row3['categoryId'] == $row2['categoryId']){ $checked = 'checked=checked'; } else { $checked = null; } echo "<input type='checkbox' name='categoryId[]' value='".$row2['categoryId']."' $checked> ".$row2['categoryName']."<br />"; } ?>

In the code lines above , we have selected the category ID which is related to the current article ID. The current ID is gated from the HTTP URL which you can see. The GET method is used to hold the current page id .

Now, add the link in the header.
Open the header.php file and add the link.


admin/header.php


Add the line after the dashboard list link .

   
  • Categories
  • Admin part is completed for blog categories .
    Let’s display the categories with the blog posts.


    blog/index.php

     echo '

    Posted on '.date('jS M Y', strtotime($row['articleDate'])).'

    ';

    Change the code line above to
    echo '

    Posted on '.date('jS M Y H:i:s', strtotime($row['articleDate'])).' in '; $stmt2 = $db->prepare('SELECT categoryName, categorySlug FROM techno_category, techno_cat_links WHERE techno_category.categoryId = techno_cat_links.categoryId AND techno_cat_links.articleId = :articleId'); $stmt2->execute(array(':articleId' => $row['articleId'])); $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC); $links = array(); foreach ($catRow as $cat){ $links[] = "<a href='category/".$cat['categorySlug']."'>".$cat['categoryName']."</a>"; } echo implode(", ", $links); echo '

    ';

    In the above code, two tables are joined together by which the categories related to the blog post are displayed with the blog post title as well as a link is given.
    Now, create another file for the category .


    blog/catlinks.php


    Just as we had created a show file to display the blog post, similarly we create the catlinks.php file for displaying blog posts related to the category.


    Lets understand the code –

     $stmt = $db->prepare('SELECT categoryId,categoryName FROM techno_category WHERE categorySlug = :categorySlug');
    $stmt->execute(array(':categorySlug' => $_GET['id']));
    $row = $stmt->fetch();
    
    //if post does not exists redirect user.
    if($row['categoryId'] == ''){
        header('Location: ./');
        exit;
    }
     

    In the code above, we are fetched categoryId, categoryName from the min category table. We use the GET method to hold the URL encoded value. If the encoded value (article id) is available then display the related blog posts.
    If the category id is not found then should be redirected to the index page
    Complete code for catlinks.php

    Complete PHP code for catlinks file


    blog/catlinks.php

     <?php require('includes/config.php'); 
    
    $stmt = $db->prepare('SELECT categoryId,categoryName FROM techno_category WHERE categorySlug = :categorySlug');
    $stmt->execute(array(':categorySlug' => $_GET['id']));
    $row = $stmt->fetch();
    
    //if post does not exists redirect user.
    if($row['categoryId'] == ''){
        header('Location: ./');
        exit;
    }
    
    
    ?>
    
    <?php include("head.php");  ?>
    
    	<?php echo $row['categoryName'];?>-Techno Smarter
    	<?php include("header.php");  ?>
    

    Article Category:- <?php echo $row['categoryName'];?>


    <?php try { $stmt = $db->prepare(' SELECT techno_blog.articleId, techno_blog.articleTitle, techno_blog.articleSlug, techno_blog.articleDescrip, techno_blog.articleDate FROM techno_blog, techno_cat_links WHERE techno_blog.articleId = techno_cat_links.articleId AND techno_cat_links.categoryId = :categoryId ORDER BY articleId DESC '); $stmt->execute(array(':categoryId' => $row['categoryId'])); while($row = $stmt->fetch()){ echo '
    '; echo '

    <a href="../'.$row['articleSlug'].'">'.$row['articleTitle'].'</a>

    '; echo '

    Posted on '.date('jS M Y H:i:s', strtotime($row['articleDate'])).' in '; $stmt2 = $db->prepare('SELECT categoryName, categorySlug FROM techno_category, techno_cat_links WHERE techno_category.categoryId = techno_cat_links.categoryId AND techno_cat_links.articleId = :articleId'); $stmt2->execute(array(':articleId' => $row['articleId'])); $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC); $links = array(); foreach ($catRow as $cat) { $links[] = "<a href='".$cat['categorySlug']."'>".$cat['categoryName']."</a>"; } echo implode(", ", $links); echo '

    '; echo '

    '.$row['articleDescrip'].'

    '; echo '

    '; echo '
    '; } } catch(PDOException $e) { echo $e->getMessage(); } ?>
    <?php include("sidebar.php"); ?> <?php include("footer.php"); ?>

    In the first tutorial, we created the .htaccess file. Open the .htaccess file and add the code line at line number 3

     RewriteRule ^category/(.*)$ catlinks.php?id=$1 [L] 

    Let's display the category title in the show.php file with the blog post title.
    Open the show.php and change the code below.


    blog/show.php

     echo '

    Posted on '.date('jS M Y', strtotime($row['articleDate'])).'

    ';

    Change the code above to

     echo '

    Posted on '.date('jS M Y H:i:s', strtotime($row['articleDate'])).' in '; $stmt2 = $db->prepare('SELECT categoryName, categorySlug FROM techno_category, techno_cat_links WHERE techno_category.categoryId = techno_cat_links.categoryId AND techno_cat_links.articleId = :articleId'); $stmt2->execute(array(':articleId' => $row['articleId'])); $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC); $links = array(); foreach ($catRow as $cat){ $links[] = "<a href='category/".$cat['categorySlug']."'>".$cat['categoryName']."</a>"; } echo implode(", ", $links); echo '

    '; echo '
    ';

    In this way, you can create the category with blog post title using PHP and MYSQL database

    Display the blog categories in Sidebar –

    categories can be displayed in the blog sidebar along with the blog post title. Open the blog sidebar and change something –

    blog/sidebar.php

    <a href="#">Blog Category 1</a>
             <a href="#">Blog Category 2</a>
                 <a href="#">Blog Category 3</a>
                     <a href="#">Blog Categories List (In the later tutorial)</a>
     

    Change the code above to

    <?php
    $stmt = $db->query('SELECT categoryName, categorySlug FROM techno_category ORDER BY categoryId DESC');
    while($row = $stmt->fetch()){
        echo '<a href="http://localhost/blog/category/'.$row['categorySlug'].'">'.$row['categoryName'].'</a>';
    }
    ?>
     

    In the code above, we are fetching all categories and displaying using a while loop with the category URL path.



    Support Us - Subscribe Now

    Recommended Posts:-

    Previous Posts:-

    Shop Items:-


    Paypal Payment form in PHP website with MYSQL database | International Payments

    $14



    Integrate Payumoney payment gateway in PHP website | Source Scripts

    $14



    Complete Blog CMS system in PHP with MYSQL database | PHP scripts

    $18







    free instagram followers free instagram likes