1

I would like to implement this like and unlike into codeigniter. I can do it in the normal php using the following codes but I just don't know how to implement it in codeigniter. any help would be appritiated. thanks.

posts table

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

like_unlike table

CREATE TABLE `like_unlike` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `userid` int(11) NOT NULL,
  `postid` int(11) NOT NULL,
  `type` int(2) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

database conn

<?php

$host = "localhost";    /* Host name */
$user = "root";         /* User */
$password = "";         /* Password */
$dbname = "tutorial";   /* Database name */

$con = mysql_connect($host, $user, $password) or die("Unable to connect");

// selecting database
$db = mysql_select_db($dbname, $con) or die("Database not found");

View

<div class="content">

  <?php
   $userid = 5;
   $query = "SELECT * FROM posts";
   $result = mysql_query($query);
   while($row = mysql_fetch_array($result)){
    $postid = $row['id'];
    $title = $row['title'];
    $content = $row['content'];
    $type = -1;

    // Checking user status
    $status_query = "SELECT count(*) as cntStatus,type FROM like_unlike WHERE userid=".$userid." and postid=".$postid;
    $status_result = mysql_query($status_query);
    $status_row = mysql_fetch_array($status_result);
    $count_status = $status_row['cntStatus'];
    if($count_status > 0){
      $type = $status_row['type'];
    }

    // Count post total likes and unlikes
    $like_query = "SELECT COUNT(*) AS cntLikes FROM like_unlike WHERE type=1 and postid=".$postid;
    $like_result = mysql_query($like_query);
    $like_row = mysql_fetch_array($like_result);
    $total_likes = $like_row['cntLikes'];

    $unlike_query = "SELECT COUNT(*) AS cntUnlikes FROM like_unlike WHERE type=0 and postid=".$postid;
    $unlike_result = mysql_query($unlike_query);
    $unlike_row = mysql_fetch_array($unlike_result);
    $total_unlikes = $unlike_row['cntUnlikes'];

   ?>
    <div class="post">
     <h1><?php echo $title; ?></h1>
     <div class="post-text">
      <?php echo $content; ?>
     </div>
     <div class="post-action">

      <input type="button" value="Like" id="like_<?php echo $postid; ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" />&nbsp;(<span id="likes_<?php echo $postid; ?>"><?php echo $total_likes; ?></span>)&nbsp;

      <input type="button" value="Unlike" id="unlike_<?php echo $postid; ?>" class="unlike" style="<?php if($type == 0){ echo "color: #ffa449;"; } ?>" />&nbsp;(<span id="unlikes_<?php echo $postid; ?>"><?php echo $total_unlikes; ?></span>)

     </div>
    </div>
   <?php
   }
   ?>

</div> 

AJAX.php

<?php

include "config.php";

$userid = 5;
$postid = $_POST['postid'];
$type = $_POST['type'];

// Check entry within table
$query = "SELECT COUNT(*) AS cntpost FROM like_unlike WHERE postid=".$postid." and userid=".$userid;
$result = mysql_query($query);
$fetchdata = mysql_fetch_array($result);
$count = $fetchdata['cntpost'];


if($count == 0){
    $insertquery = "INSERT INTO like_unlike(userid,postid,type) values(".$userid.",".$postid.",".$type.")";
    mysql_query($insertquery);
}else {
    $updatequery = "UPDATE like_unlike SET type=" . $type . " where userid=" . $userid . " and postid=" . $postid;
    mysql_query($updatequery);
}


// count numbers of like and unlike in post
$query = "SELECT COUNT(*) AS cntLike FROM like_unlike WHERE type=1 and postid=".$postid;
$result = mysql_query($query);
$fetchlikes = mysql_fetch_array($result);
$totalLikes = $fetchlikes['cntLike'];

$query = "SELECT COUNT(*) AS cntUnlike FROM like_unlike WHERE type=0 and postid=".$postid;
$result = mysql_query($query);
$fetchunlikes = mysql_fetch_array($result);
$totalUnlikes = $fetchunlikes['cntUnlike'];

// initalizing array
$return_arr = array("likes"=>$totalLikes,"unlikes"=>$totalUnlikes);

echo json_encode($return_arr);

Jquery

$(document).ready(function(){

    // like and unlike click
    $(".like, .unlike").click(function(){
        var id = this.id;   // Getting Button id
        var split_id = id.split("_");

        var text = split_id[0];
        var postid = split_id[1];  // postid

        // Finding click type
        var type = 0;
        if(text == "like"){
            type = 1;
        }else{
            type = 0;
        }

        // AJAX Request
        $.ajax({
            url: 'likeunlike.php',
            type: 'post',
            data: {postid:postid,type:type},
            dataType: 'json',
            success: function(data){
                var likes = data['likes'];
                var unlikes = data['unlikes'];

                $("#likes_"+postid).text(likes);        // setting likes
                $("#unlikes_"+postid).text(unlikes);    // setting unlikes

                if(type == 1){
                    $("#like_"+postid).css("color","#ffa449");
                    $("#unlike_"+postid).css("color","lightseagreen");
                }

                if(type == 0){
                    $("#unlike_"+postid).css("color","#ffa449");
                    $("#like_"+postid).css("color","lightseagreen");
                }


            }

        });

    });

});

I would be grateful if someone could show me how to implement this in codeigniter Thanks in advance.

MaverickD
  • 33
  • 5
  • 1
    [**Please, don't use `mysql_*` functions in new code**](http://stackoverflow.com/q/12859942). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://php.net/mysql-connect)? Learn about [*prepared statements*](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://php.net/manual/en/mysqlinfo.api.choosing.php) can help you decide which. – Qirel Jul 24 '17 at 19:59
  • Noted. Please do you have a solution for the question? – MaverickD Jul 24 '17 at 20:02
  • @MaverickD Codeigniter has its own database.php in config once add dataabase there then autoload the database library http://www.codeigniter.com/user_guide/database/connecting.html also the query builder is good http://www.codeigniter.com/user_guide/database/query_builder.html –  Jul 24 '17 at 20:39
  • I am familiar with the codeigniter database. I just do not know how to transform this my code into a codeigniter MVC thing. – MaverickD Jul 24 '17 at 20:46

1 Answers1

0

step 1) setup database config in /application/config/database.php

step 2) create a controller i named it as Welcome.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

  public function show_posts()
  {
    $this->load->model('posts_model');

    $uid = 5; //user id

    $posts = $this->posts_model->count_likes_and_unlikes($uid);
    $this->load->view('posts_view',['posts' => $posts]);
  }
} 

step 3) Create a Model called Posts_model.php

<?php  

class Posts_model extends CI_Model
{      
  public function __construct()
  {
      parent::__construct();
      $this->load->database();
  }


  // retrive all posts from table posts
  public function get_posts()
  {
    return $this->db->get('posts');
  }


  // return posts with like ,unlike counts 
  public function count_likes_and_unlikes($uid)
  {
    $userid = $uid;
    $posts = $this->get_posts()->result_array();

    foreach ($posts as &$post) 
    {

      $post['type'] = -1;
      $status_row = $this->db->query("SELECT * FROM like_unlike WHERE userid=".$userid." and postid=".$post['id']);

      if($status_row->num_rows() > 0)
      {
        $post['type'] = $status_row->result_array()[0]['type'];
      }


      // Count post total likes and unlikes
      $like_query = "SELECT COUNT(*) AS cntLikes FROM like_unlike WHERE type=1 and postid=".$post['id'];
      $like_row = $this->db->query($like_query);
      $post['total_likes'] = $like_row->num_rows();


      $unlike_query = "SELECT COUNT(*) AS cntUnlikes FROM like_unlike WHERE type=0 and postid=".$post['id'];
      $unlike_row = $this->db->query($unlike_query); 
      $post['total_unlikes'] = $unlike_row->num_rows();

    }
    // return array of posts to controller
    return $posts;
  }
}

step 4) Create View called posts_view.php in applications/view

<div class="content">

<?php foreach ($posts as $post):?>
  <div class="post">

     <h1><?php echo $post['title']; ?></h1>

     <div class="post-text">
      <?php echo $post['content']; ?>
     </div><!-- ./ post-text -->

     <div class="post-action">

      <input type="button" value="Like" id="like_<?php echo $post['id']; ?>" class="like" style="<?php if($post['type'] == 1){ echo "color: #ffa449;"; } ?>" />&nbsp;(<span id="likes_<?php echo $post['id']; ?>"><?php echo $post['total_likes']; ?></span>)&nbsp;

      <input type="button" value="Unlike" id="unlike_<?php echo $post['id']; ?>" class="unlike" style="<?php if($post['type'] == 0){ echo "color: #ffa449;"; } ?>" />&nbsp;(<span id="unlikes_<?php echo $post['id']; ?>"><?php echo $post['total_unlikes']; ?></span>)

     </div> <!-- ./ post-action -->

    </div> <!-- ./ post -->
   <?php endforeach; ?>

</div> 

step 5) change ajax url to url: 'Welcome/show_posts'

Jayakrishnan
  • 1,295
  • 2
  • 13
  • 27