使用jQuery和OOP PHP创建Like按钮

时间:2016-03-04 14:47:56

标签: php jquery oop

我试图创建一个" Like"我从我的数据库中打印出来的一些文章的按钮。但是我被卡住了。

我达到了从jQuery发布投票的地步,我得到一个空的VAR_DUMP。

在我的OOP课程中,当我将它们保存在数据库中时,我不确定如何打印出选票。

这是我的代码

HTML

   <?php
 // IF theres is a id in adress field
 //if(isset($_GET['id'])) {
$page = new CMS();
$gp = $page->getPage();


foreach ($gp as $sp) {
  //var_dump($sp);

  echo "<div class='pub'>";
  echo "<h4 class='pub-headline'>" . $sp['title'] . "</h4>"; 
  echo "<article class='pub_art'>" . $sp['content'] . "</article>";  
  echo "<p class='pub_created'>" . $sp['created'] . "</p>"; 
  echo "<p class='pub_created_by'>". $sp['writer'] ."</p>";
  echo "<button class='show'>Show</button>"; 
  echo "<button class='noshow'>Hide</button>";

  echo "<button class='btn-like'>Like</button>"; // Here  is my button

  echo "</div>";

}
?>

的jQuery

  /* --------------------Selecting article----------------------*/

  // Calling for the method - likes
  $(".btn-like").on("click", like);  


 function like(e) {
    e.preventDefault();

        // Declaring variables
    var id=$(id).val();
    var likes=$(".btn-like").val();


    console.log('Click Click..'); 

     $.post('classCalling4.php', {

        id: id,
        likes: likes }, 

        function(data){
            console.log(data);

            }); 

    }

PHP

   var_dump($_POST); // ***** This VAR_DUMP is getting back to me empty  


   if(isset($_POST['id'])) {

    //echo "rätt...";

    $id = $_POST['id'];
    $likes = $_POST['likes'];

    $id = intval($id);
    $likes = intval($likes);


    $ul = new updateLikes();

    if($ul->updateLikes($_POST['id'], $_POST['likes'])) {

        echo "Created";
    } 
    else {

    } echo "noooo";
}
?>

最后我的OOP课程,不完整,因为我被卡住了。

  public function updateLikes($id, $likes) {


    $stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
    $stmt->bind_param("ii", $likes, $id);

    if($stmt->execute()) {
        echo "win";
    } else {
        echo "lost";
    }
   }

1 个答案:

答案 0 :(得分:0)

至少你的OOP类有一些错误:

$stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
$stmt->bind_param("ii", $likes, $id);

应该是:

$stmt = $this->db->prepare('UPDATE pages SET likes = likes + :likes, WHERE id = :id');
$stmt->bind_param(":likes", $likes);
$stmt->bind_param(":id", $id);

或者如果意思是增加喜欢只有一个,那么:

$stmt = $this->db->prepare('UPDATE pages SET likes = likes + 1, WHERE id = :id');
$stmt->bind_param(":id", $id);

如果var_dump没有返回任何内容,那么PHP代码中可能会出错(导致错误代码500并且取决于PHP设置PHP可能会返回空白页)