Mysql
 sql >> Database >  >> RDS >> Mysql

php - Abilitazione degli utenti ai post preferiti

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

Inoltre, tieni presente che in PHP le funzioni mysql_* sono state deprecate e non sono sicure da usare (consentono attacchi SQL Injection). Scopri di più sul PDO qui:http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059