实现php喜欢和不同的功能到codeigniter

时间:2017-07-24 19:57:36

标签: php jquery ajax codeigniter

我想像codeigniter一样实现它。我可以使用以下代码在普通的php中完成它,但我只是不知道如何在codeigniter中实现它。任何帮助都会受到批评。感谢。

发布表

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;

数据库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");

查看

<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");
                }


            }

        });

    });

});

如果有人能告诉我如何在 codeigniter 中实现这一点,我将不胜感激。提前致谢。

1 个答案:

答案 0 :(得分:0)

步骤1)在/application/config/database.php

中设置数据库配置

步骤2)创建一个控制器,我将其命名为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]);
  }
} 

步骤3)创建名为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;
  }
}

步骤4)在posts_view.php

中创建名为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> 

步骤5)将ajax网址更改为url: 'Welcome/show_posts'