Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi. At the outset, let me say that just starting to program and sorry for my bad English. Anyway.
This code is used to like system. I don't know why this code doesn't working.

Code:
PHP
<?php
    $mysqli = new mysqli('localhost', 'root','');
    $mysqli->select_db('like');

    if(isset($_POST['liked']))
    {
        $postid = $_POST['postid'];
        $result = mysqli_query("SELECT * FROM posts WHERE postid=$postid");
        $row = mysqli_fetch_array($result);
        $n = $row['likes'];

        mysqli_query("UPDATE posts SET likes=$n+1 WHERE id=$postid ");
        mysqli_query("INSERT INTO likes(userid, postid) VALUES(1,$postid)");
        exit();
    }
?>

<!DOCTYPE html>
<html>
<head>
    <title>LIKE and UNLIKE</title>
    <style type="text/css">
        .content
        {
            width:50%;
            margin:100px auto;
            border:1px solid #cbcbcb;
        }
        .post
        {
            width:80%;
            margin:10px auto;
            border:1px solid #cbcbcb;
            padding:10px;
        }
    </style>
</head>
<body>
    <div class="content">
      <?php
         $query = $mysqli->query("SELECT * FROM posts");
    
        while($row = mysqli_fetch_array($query)) { ?>
        <div class="post">
            <?php echo $row['text']; ?> <br>

            <?php      
                $result = mysqli_query($mysqli,"SELECT * FROM likes WHERE userid='1' AND postid=".$row['id']."");
                
                if(mysqli_num_rows($result) == 1) { ?>
                
                    <span><a href="" class="unlike" id="<?php echo $row['id']; ?>">unlike</a></span>
          <?php } else{ ?>
                         <span><a href="" class="like" id="<?php echo $row['id']; ?>">like</a></span>
           <?php } ?>
        </div>
       <?php } ?>

    </div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function(){       
            $('.like').click(function(){
                var postid = $(this).attr('id');
                $.ajax({
                    url:'index.php',
                    type: 'post',
                    async: false,
                    data:{
                        'liked': 1,
                        'postid': postid
                    }
                    success:function(){

                    }
                });
            });
        });
</script>
</body>
</html>


Table sql:

likes.sql

SQL
CREATE TABLE `likes` (
  `id` int(11) NOT NULL,
  `userid` int(11) NOT NULL,
  `postid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1


posts.sql

SQL
CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `text` text NOT NULL,
  `likes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1


users.sql
SQL
CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(55) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


What I have tried:

I tried change code:
PHP
<?php

    if(!isset($_POST['liked']))
    {
        $postid = $_POST['postid'];
        $result = mysqli_query($mysqli,"SELECT * FROM likes WHERE postid='$postid'");
        $row = mysqli_fetch_array($result) or die("ERROR: ".mysqli_error($mysqli));
        $n = $row['likes'];

        $result = mysqli_query($mysqli,"UPDATE posts SET likes=$n+1 WHERE id=$postid ");
        $result = mysqli_query($mysqli,"INSERT INTO likes (userid, postid) VALUES(1,$postid)");
        exit();
    }
    ?>
Posted
Updated 18-Mar-17 6:27am
Comments
ZurdoDev 17-Mar-17 14:51pm    
You have to explain what is not working. What should it do? What is it not doing? What error is there? Click Improve question and add information.
Patrice T 17-Mar-17 16:13pm    
Define "doesn't working"

ok, assuming the connection to MySQL database is working.
Here are my recommendations:

1. Syntax error on the AJAX call, need to have a comma (,) after the data
2. Move the update/insert into a separate script
3. There is no postid in table post, should be id
4. the mysqli_query, you did it correctly in the index.php by including the connection string in the function. but not sure why you wouldn't do the same in the post/update
5. there are lots of other improvement you need to make such as, prevent SQL injection or XSS, place the connectionstring into a separate file, etc...

Here are the updated code:
PHP
<?php
    $mysqli = new mysqli('localhost', 'root','');
    $mysqli->select_db('like');   
?>
<!DOCTYPE html>
<html>
<head>
    <title>LIKE and UNLIKE</title>
    <style type="text/css">
        .content
        {
            width:50%;
            margin:100px auto;
            border:1px solid #cbcbcb;
        }
        .post
        {
            width:80%;
            margin:10px auto;
            border:1px solid #cbcbcb;
            padding:10px;
        }
    </style>
</head>
<body>
    <div class="content">
      <?php
         $query = $mysqli->query("SELECT * FROM posts");
    
        while($row = mysqli_fetch_array($query)) { ?>
        <div class="post">
            <?php echo $row['text'] . " " . $row['likes']; ?> <br>

            <?php      
                $result = mysqli_query($mysqli,"SELECT * FROM likes WHERE userid='1' AND postid=".$row['id']."");
                
                if(mysqli_num_rows($result) == 1) { ?>
                
                    <span><a href="" class="unlike" id="<?php echo $row['id']; ?>">unlike</a></span>
          <?php } else{ ?>
                         <span><a href="" class="like" id="<?php echo $row['id']; ?>">like</a></span>
           <?php } ?>
        </div>
       <?php } ?>

    </div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function(){       
            $('.like').click(function(){
                var postid = $(this).attr('id');
                $.ajax({
                    url:'index_post.php',
                    type: 'post',
                    async: false,
                    data:{
                        'liked': 1,
                        'postid': postid
                    },
                    success:function(){
                    }
                });
            });
        });
</script>
</body>
</html>

index_post.php
PHP
<?php
    $mysqli = new mysqli('localhost', 'root','');
    $mysqli->select_db('like');

     $postid = $_POST['postid'];
        $result = mysqli_query($mysqli, "SELECT * FROM posts WHERE id=$postid");
	while($row2 = $result->fetch_array())
	  {
		$n = $row2['likes'];
		
		mysqli_query($mysqli, "UPDATE posts SET likes=$n+1 WHERE id=$postid");
	   
	   mysqli_query($mysqli, "INSERT INTO likes(userid, postid) VALUES(1,$postid)");
	  }	
        exit();
?>
 
Share this answer
 
Comments
Mike CJ 18-Mar-17 9:54am    
Okay, working, Now I need something such as "if the user clicked on the button" unlike "change the button to" like "in this case is the link "href". How I can do it?
Bryian Tan 18-Mar-17 10:13am    
I though your code is doing that now, if count of like for a post not equal to one, show he unlike link? The easiest way without complication to accomplish is to duplicate your current javascript to $('.unlike').click(function(){ ... }. On the post call a different URL like url:'index_post_unlike.php'. Then in that page just reverse engineer the content in index_post.php
Mike CJ 18-Mar-17 10:40am    
I created index_unpost.php Javascript:
$(document).ready(function(){
$('.unlike').click(function(){
var postid = $(this).attr('id');
$.ajax({
url:'index_unpost.php',
type: 'post',
async: false,
data:{
'unliked': 1,
'postid2': postid
},
success:function(){

}
});
});
});

And code in the index_unpost.php
<?php
$mysqli = new mysqli('localhost', 'root','');
$mysqli->select_db('like');

$postid = $_POST['postid'];
$result = mysqli_query($mysqli, "SELECT * FROM posts WHERE id=$postid");
while($row3 = $result->fetch_array())
{
$n = $row3['likes'];

mysqli_query($mysqli, "DELETE FROM likes WHERE id=$postid userid=1");
mysqli_query($mysqli, "UPDATE posts SET likes=$n-1 WHERE id=$postid");
}
exit();
?>
If the user clicks the button like such as in the table is reduced by 1, but the "unlike" does not change to like. I don't know why.
Bryian Tan 18-Mar-17 10:50am    
the AJAX is posting
data:{
'unliked': 1,
'postid2': postid
},

but the php code is reading using this code $postid = $_POST['postid'];
it should be $postid = $_POST['postid2'];
Mike CJ 18-Mar-17 11:00am    
Okay. But button does not change the like but is still unlike. Why?
index.php
PHP
<?php
    $mysqli = new mysqli('localhost', 'root','');
    $mysqli->select_db('like');   
?>
<!DOCTYPE html>
<html>
<head>
    <title>LIKE and UNLIKE</title>
    <style type="text/css">
        .content
        {
            width:50%;
            margin:100px auto;
            border:1px solid #cbcbcb;
        }
        .post
        {
            width:80%;
            margin:10px auto;
            border:1px solid #cbcbcb;
            padding:10px;
        }
    </style>
</head>
<body>
    <div class="content">
      <?php
         $query = $mysqli->query("SELECT * FROM posts");
    
        while($row = mysqli_fetch_array($query)) { ?>
        <div class="post">
            <?php echo $row['text'] . " " . $row['likes']; ?> <br>

            <?php      
                $result = mysqli_query($mysqli,"SELECT * FROM likes WHERE userid='1' AND postid=".$row['id']."");
                
                if(mysqli_num_rows($result) == 1) { ?>
                
                    <span><a href="" class="unlike" id="<?php echo $row['id']; ?>">unlike</a></span>
          <?php } else { ?>
          
                         <span><a href="" class="like" id="<?php echo $row['id']; ?>">like</a></span>
           <?php } ?>

        </div>
       <?php } ?>

    </div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function(){       
            $('.like').click(function(){
                var postid = $(this).attr('id');
                $.ajax({
                    url:'index_post.php',
                    type: 'post',
                    async: false,
                    data:{
                        'liked': 1,
                        'postid': postid
                    },
                    success:function(){
                    }
                });
            });
        });
        </script>
        
        <script type="text/javascript">
        $(document).ready(function(){                         
        $('.unlike').click(function(){
        var postid = $(this).attr('id');
        $.ajax({
        url:'index_unpost.php',
        type: 'post',
        async: false,
        data:{
        'unliked': 1,
        'postid2': postid
        },
        success:function(){

         }
      });
   });
});
</script>
</body>
</html>



index_post.php
PHP
<?php
    $mysqli = new mysqli('localhost', 'root','');
    $mysqli->select_db('like');

     $postid = $_POST['postid'];
     $result = mysqli_query($mysqli, "SELECT * FROM posts WHERE id=$postid");
     while($row2 = $result->fetch_array())
	 {
		$n = $row2['likes'];
		
		mysqli_query($mysqli, "UPDATE posts SET likes=$n+1 WHERE id=$postid");
	    mysqli_query($mysqli, "INSERT INTO likes(userid, postid) VALUES(1,$postid)");
	  }	
        exit();
?>



index_unpost.php
PHP
<?php
    $mysqli = new mysqli('localhost', 'root','');
    $mysqli->select_db('like');

     $postid = $_POST['postid2'];
     $result = mysqli_query($mysqli, "SELECT * FROM `posts` WHERE id=$postid");
	while($row3 = $result->fetch_array())
	  {
		$n = $row3['likes'];

        
		mysqli_query($mysqli, "UPDATE `posts` SET likes=$n-1 WHERE postid=$postid AND userid=1");
        mysqli_query($mysqli, "DELETE FROM `likes` WHERE id='$postid' userid=1 ");
	  }	
        exit();
?>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900