Creating a complete blog (CRUD) using MySQL and PHP – Part 2

Datetime:2016-08-23 02:20:21          Topic: PHP  MySQL           Share

In theprevious part, we created a Post Class which will handle our article request and perform CRUD operation on it. In this tutorial, we are going to use the same class and will insert, update and delete articles.

We are going to make forms for insert and update article, create a view for article and a page where all the articles will be listed and can be deleted. I will be using bootstrap for styling. Let’s get started:

Header & Footer For View

First we are going to create a header and a footer for our pages. Now in the same folder, create a new file header.php and paste the following code in it.

<!DOCTYPE html PUBLIC "-#W3C#DTD XHTML 1.0 Transitional#EN" "http:#www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html xmlns="http:#www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
         <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Blog System</title>
        <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
        
        
    </head>
    <body class="container-fluid">
            <div class="container-fluid">

Now create a new file footer.php and paste the following code in it.

<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>



</div>

</body>
</html>

Insert A New Post

Now lets create a form which will insert a new post into database and connect it with Post Class. Before creating form create a new folder in the same directory and name it postimages in order to save all the images in it. Now create a new file and name it index.php and post the following code in it.

<?php
include 'header.php';

echo 'Posted';

include 'footer.php';

?>

In this file we will redirect the user when the post is published successfully. Now lets create a new file creatpost.php and paste the following code in it.

<?php

include 'header.php';
include 'postclass.php';
        
$crud   = new Post();
$errors = [
    'article_name'     => null,
    'article_category' => null,
    'article_content'  => null,
    'article_img'      => null,
    'form'             => null,
];

$conne         = '';
$form          = true;
$target_dir    = "postimages/";
$target_file   = null;
$imageFileType = null;
if (!empty($_POST)) {

    $target_file   = $target_dir . basename($_FILES["article_img"]["name"]);
    $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
    $check         = getimagesize($_FILES["article_img"]["tmp_name"]);
    if (empty($_POST['a_name'])) {
        $errors['article_name'] = "Please Enter Your Title";
        $form                   = false;
    }
    if ($check === false) {
        $errors['article_img'] = 'Image is required';
        $form                  = false;
    } elseif ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
        $errors['article_img'] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.';
        $form                  = false;
    }

    if (empty($_POST['article_content'])) {
        $errors['article_content'] = "Please Fill Your Content";
        $form                      = false;
    }

    if ($form) {

        $articlename = $_POST['a_name'];
        $articlecont = $_POST['article_content'];
        
        $image       = rand(1, 100);
        $imgname     = $image . "." . $imageFileType;
        $result      = $crud->insertpost($articlename, $articlecont, $imgname);

        if ($result == 'true') {
            move_uploaded_file($_FILES["article_img"]["tmp_name"], $target_dir . $imgname);
            header('Location: index.php');
            return;
        } else {
            $errors['form'] = $result;
        }

    }

} else {
    $errors['form'] = "Kindly Fill All the Fields";
}

?>
<!--<script type="text/javascript" src="tinymce/tinymce.min.js"></script>-->
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
    <script type="text/javascript">
        // tinymce.init({
        //     selector: "#article_content"
        // });

bkLib.onDomLoaded(function() {
  new nicEditor().panelInstance('article_content');

});
    </script>

<form class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<fieldset>

<!-- Form Name -->
<legend>Create Post</legend>

<!-- Text input-->
<div class="form-group col-md-10">
  <label class="control-label" for="a_name">Create Post</label>

  <input id="a_name" name="a_name" type="text" placeholder="Enter Title For Your Article" class="form-control input-md"  value="<?php if (isset($_POST['a_name'])) {echo $_POST['a_name'];}
?>" required>
    <p class="text-danger"><?php echo $errors['article_name'] ?></p>

</div>

<!-- File Button -->
<div class="form-group col-md-10">
  <label class="control-label" for="article_img">Upload Image</label>

    <input id="article_img" name="article_img" class="input-file" type="file" required>

     <p class="text-danger"><?php echo $errors['article_img'] ?></p>

</div>

<!-- Textarea -->
<div class="form-group col-md-10" >
  <label class="control-label" for="article_content">Content</label>

    <textarea class="form-control" id="article_content" name="article_content" rows="13"><?php if (isset($_POST['article_content'])) {echo $_POST['article_content'];}
?></textarea>
    <p class="text-danger"><?php echo $errors['article_content'] ?></p>

</div>

<!-- Button -->
<div class="form-group col-md-10">
  <label class="control-label" for="submit"></label>

    <button id="submit" name="submit" type="submit" class="btn btn-success">Publish</button>
    <p class="text-danger"><?php echo $errors['form'] ?></p>

</div>

</fieldset>
</form>


<?php include 'footer.php';?>

In the above code we have created a form and also done its validation so that it doesn’t send empty data in database. Then if the data is submitted to database we will upload its image on our server.

Now run it on your browser by going to your root folder and then to createpost.php.It will look like this:

Try sending a post, if it has no error you will be transferred to the succeed page and you can also check on your database to verify that your post is edited.

Now let’s create a page where these posts will be listed.

View Publish Post

Now go to the file in your directory and name it postview.php and paste the following code in it.

<?php
include 'header.php';
include 'postclass.php';

$postid = $_GET['postid'];

$article = new Post();
$result  = $article->getarticle($postid);

?>
<div class='row'>
<?php
while ($row = $result->fetch_assoc()) {
    ?>
  <div class="panel panel-default">
  <div class="panel-heading back">
    <h2> <?php echo $row['article_name'];?> </h2>
    <h5><span class="glyphicon glyphicon-time"></span> Posted On <?php echo $row['dates'];?></h5>
      
  </div>
  <div class="panel-body">
    <div class="col-md-3 pull-right">
    <img class='img-responsive img-rounded center' src="postimages/<?php echo $row['img'];?>">
    </div>
   <?php echo $row['article_content'];?>
  </div>
</div>
<?php
}
?>
</div>


  <?php
include 'footer.php';
?>

What we did in this code is that we get the ID of the post and then call our getarticle() method and view the article on the browser.

Give it a try by running the above file and pass your postid in it by url and you will get a view of your post

Now that we have viewed our post, let’s update it.

Updating A Post

Now let’s edit our post. We will get the id of the post and paste it to our getarticle() method to get the previous article and view it in the editor to use. Then when clicked on update the article we will call updatearticle() method.

Now create a new file updatepost.php in the same directory and paste the following code:

<?php
include 'header.php';
include 'postclass.php';
$user = $_SESSION["username"];
$aid = null;

if(empty($_POST))
{
  $aid = $_GET['postid'];
}
else{
  $aid = $_POST['postid'];
}


$crud = new Post();
$errors = [
        'article_name' => null,
        'article_category' => null,
        'article_content' => null,
        'article_img' => null,
        'form' => null
    ];
$article = [
        'a_id' => $aid,
        'a_name' => null,
        'a_con' => null,
        'a_img' => null,
        'form' => null
    ];

    $result = $crud->getarticle($aid);

    while($row = $result->fetch_assoc())
        {
          $article['a_name'] = $row['article_name'];
          $article['a_con'] = $row['article_content'];
          $article['a_img'] = $row['img'];
        }

    $conne='';
    $form = true;
    $target_dir = "postimages/";
    $target_file = null;
    $imageFileType = null;
    $Upload = false;

  //  var_dump($article);
if(!empty($_POST))
{	
	
	$target_file = $target_dir . basename($_FILES["article_img"]["name"]);
	$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
  $check = false;
	$check = getimagesize($_FILES["article_img"]["tmp_name"]);

	if($_POST['a_name'] !== $article['a_name'])
	{
		$article['a_name'] = $_POST['a_name'];
	
	}
	if ($check !== false)
	{
  	$Upload = true;
	if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" ) 
	{
	   $errors['article_img'] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.';
	   $form =false;
	}
  }

	if($_POST['article_content'] !== $article['a_con'])
	{
		$article['a_con'] = $_POST['article_content'];
		
	}

if($form)
{
  
  
  if($Upload)
  {
            $image = rand(1,100);
            $imgname = $image .".".$imageFileType;
            $result = $crud->updatearticle($article['a_id'],$article['a_con'],$article['a_name'],$imgname);
          if($result == 'true')
              {
                move_uploaded_file($_FILES["article_img"]["tmp_name"], $target_dir.$imgname);
                          header("Location: postview.php?postid=$aid");
                               return;
              }
          else
              {
                $errors['form'] = $result;
              }
  }
  else
  {
          var_dump($article);
          $result =  $crud->updatearticle($article['a_id'],$article['a_con'],$article['a_name'],$article['a_img']);
          if($result == 'true')
              {
                
               header("Location: postview.php?postid=$aid");
                               return;
              }
          else
              {
                $errors['form'] = $result;
              }
  }

  
	
}

}
else
{
	$errors['form'] = "Kindly Fill All the Fields";
}


?>
<!--<script type="text/javascript" src="tinymce/tinymce.min.js"></script>-->
<script type="text/javascript" src="style/js/nicEdit.js"></script>
    <script type="text/javascript">
        // tinymce.init({
        //     selector: "#article_content"
        // });

bkLib.onDomLoaded(function() {
  new nicEditor().panelInstance('article_content');
  
});
    </script>

<form class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<input type="hidden" name="postid" value="<?php echo $_GET['postid']?>">
<!-- Form Name -->
<legend>Update Article</legend>

<!-- Text input-->
<div class="form-group col-md-10">
  <label class="control-label" for="a_name">Title</label>  
  
  <input id="a_name" name="a_name" type="text" placeholder="Enter Title For Your Article" class="form-control input-md"  value="<?php echo $article['a_name'];  ?>" required>
    <p class="text-danger"><?php echo $errors['article_name']?></p>
  
</div>

<!-- File Button --> 
<div class="form-group col-md-10">
  <label class="control-label" for="article_img">Upload Image</label>
  
    <input id="article_img" name="article_img" class="input-file" type="file" value="<?php echo $article['a_img']?>">

     <p class="text-danger"><?php echo $errors['article_img']?></p>
  
</div>

<!-- Textarea -->
<div class="form-group col-md-10" >
  <label class="control-label" for="article_content">Content</label>
                      
    <textarea class="form-control" id="article_content" name="article_content" rows="13"><?php echo $article['a_con'];  ?></textarea>
    <p class="text-danger"><?php echo $errors['article_content']?></p>
  
</div>

<!-- Button -->
<div class="form-group col-md-10">
  <label class="control-label" for="submit"></label>
 
    <button id="submit" name="submit" class="btn btn-success">Update</button>
    <a href="articlelist" id="cancel" name="cancel" class="btn btn-danger">Cancel</a>
    <p class="text-danger"><?php echo $errors['form']?></p>
  
</div>

</fieldset>
</form>


<?php include 'footer.php';?>

As I’ve said before, we get the postid, update it and then we redirect it to postview if it is successfully updated. Give it a try!

Delete A Post

Deleting a post is quite easy. We just get the postid, paste it to our deletearticle() method and delete the post. Now create a new file in the the same directory and name it delete.php and paste the following code in it:

<?php 
include 'postclass.php';

$ids = $_GET['postid'];

$del = new Post();

$result = $del->deletearticle($ids);

if($result === true)
{
	echo "Post Is Deleted Successfully";
}
else
{
	echo $result;
}




?>

Give it a try and delete your post.

Conclusion

This is the 2nd and last part of the tutorial series in which we used our postclass to perform crud operations on our blog. All the codes can be found in the github repository . Fork it and feel free to add more things in it or clone it to use it in your projects.





About List