PHP
<?php
session_start();
require_once('connection.php');
mysql_select_db($database_connection, $connection);
$query_favorite = "SELECT username, post_id FROM favorite";
$favorite = mysql_query($query_favorite, $connection) or die(mysql_error());
$row_favorite = mysql_fetch_assoc($favorite);
$totalRows_favorite = mysql_num_rows($favorite);
if(in_array($_POST['id'], $row_favorite))
{
//is already favourited, run a query to remove that row from the db, so it won't be favorited anymore
}
else
{
//post is not favourited already, run a query to add a new favourite to the db.
}
?>
HTML
<a href="#" class="favourite" data-id="<?php echo $post_id; ?>">Favourite</a>
jQuery
$(document).ready(function() {
$('.favourite').on('click', null, function() {
var _this = $(this);
var post_id = _this.data('id');
$.ajax({
type : 'POST',
url : '/file.php',
dataType : 'json',
data : 'id='+ post_id,
complete : function(data) {
if(_this.siblings('.typcn-star-outline'))
{
_this.html('<span class="typcn typcn-star-full-outline"></span>Favourite');
}
else
{
_this.html('<span class="typcn typcn-star-outline"></span>Favourited');
}
}
});
});
});
Juga, harap dicatat bahwa dalam PHP fungsi mysql_* telah ditinggalkan dan tidak aman untuk digunakan (mereka memungkinkan serangan SQL Injection). Pelajari lebih lanjut tentang PDO di sini:http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059