jquery - php - Enabling users to favorite posts -
on website want allow users favorite posts. logged in user directed page shows posts , under each 1 placed hyperlink favorite. want text change favorite favorited , other way around. how do that?
html , php
<?php session_start(); require_once('connection.php'); mysql_select_db($database_connection, $connection); $query_favorite = "select username, post_id favorite"; $favorite = mysql_query($query_favorite, $connection) or die(mysql_error()); $row_favorite = mysql_fetch_assoc($favorite); $totalrows_favorite = mysql_num_rows($favorite); ?> <a href="#" class="favourite">favourite</a>
tables in datatbase
create table `user` ( `username` varchar(45) not null, `email` varchar(45) not null, `password` varchar(45) not null, `profilepic` varchar(50) default null, primary key (`username`) ) engine=innodb default charset=utf8 create table `post` ( `post_id` int(11) not null auto_increment, `title` varchar(100) not null, `dato` date not null, `category` varchar(100) not null, `description` varchar(500) not null, `text` longtext not null, primary key (`post_id`), ) engine=innodb auto_increment=10 default charset=utf8 create table `favorite` ( `username` varchar(45) not null, `post_id` int(11) not null, primary key (`username`,`post_id`), key `fk_favorite_post1_idx` (`post_id`), constraint `fk_favorite_user` foreign key (`username`) references `user` (`username`) on delete no action on update no action, constraint `fk_favorite_post1` foreign key (`post_id`) references `post` (`post_id`) on delete no action on update no action ) engine=innodb default charset=utf8
php
<?php session_start(); require_once('connection.php'); mysql_select_db($database_connection, $connection); $query_favorite = "select username, post_id 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 favourited, run query remove row db, won't favorited anymore } else { //post not favourited already, run query add new favourite 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'); } } }); }); });
also, please note in php mysql_* functions have been deprecated , unsafe use (they allow sql injection attacks). learn more pdo here: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Comments
Post a Comment