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
$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
$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();
?>