I'm trying to build a CMS where I can click a star icon and it will change the art_featured value in my database, so say if art_featured value is 0 and I click my star icon I want to change the value of the field from 0 to 1. I kind of have it working but I don't know how to pass the art_featured value, usually I would just us the id on my span but I'm already using that so I can tell which article I need to change, so how can I get the value of art_featured to my SQL statement so I can run a if and else statement and then run a certain SQL statement depending on the value of art_featured,
Thanks in advance for any help!
TABLE
art_id art_title art_company art_featured
1 lorem 1 lorem ipsum 1 1
2 lorem 2 lorem ipsum 2 0
HTML/PHP
<section class="row">
<?php
$sql_categories = "SELECT art_title, art_company, art_id, art_featured FROM app_articles";
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row">
<div class="column two"><p><?php echo $row['art_title']; ?></p></div>
<div class="column two"><p><?php echo $row['art_company']; ?></p></div>
<div class="column one"><span id="<?php echo $row['art_id']; ?>" class="icon-small star"></span></div>
</div>
<?php
}
}
else {
echo "FAIL";
}
?>
</section>
jQuery
$(".star").click(function(){
var art_id = $(this).attr('id');
$.ajax({
type: "POST",
data: {art_id:art_id},
url: "ajax-feature.php",
success: function(data){
if(data != false) {
}
else {
}
}
});
});
mySQL / PHP
if(isset($_POST['art_id'])) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
if(query($sql_articles)) {
echo "YES";
}
else {
echo "NO";
}
}
else {
echo "FAIL";
}
$sql_detail = "SELECT * FROM app_articles
WHERE art_id = " . $_POST['art_id'];
$sql_result = mysql_query($sql_detail);
if(mysql_num_rows($sql_result) > 0) { // the art_id supplied exists
while($sR = mysql_fetch_array($sql_result)) {
$art_title = $sR['art_title'];
$art_company = $sR['art_company'];
$art_featured = $sR['art_featured];
// Do whatever you want with these variables
}
} else { // the art_id supplied does not exist
}
It's unsafe to pass the $_POST['art_id'] directly into a SQL statement, so you should probably read up on data sanitation. But this should do.
Related
Below is the index page: having these code: Data gets populated in a div as expected.
<h2>Search for users</h2>
<input type="text" name="search" id="search" autocomplete="off" placeholder="Enter Customer ID here....">
<div id="output"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
var query = $(this).val();
if (query != "") {
$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {query:query},
success: function(data){
$('#output').html(data);
$('#output').css('display', 'block');
$("#search").focusin(function(){
$('#output').css('display', 'block');
});
}
});
} else {
$('#output').css('display', 'none');
}
});
});
</script>
This is the ajax-db-search.php page. (In the IF tags I tried it with == and no good luck yet.)
<?php
$conn=mysqli_connect("*****","*********","******","*****");
$query = "SELECT * FROM `create_customer` WHERE `Customer Id` LIKE '{$_POST['query']}%' LIMIT 6";
$result = mysqli_query($conn, $query);
$plan = $query['Plan'];
if ($plan = "planA") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planA_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
var_dump ($plan);
}
}
if ($plan = "planB") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planB_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
if ($plan = "planC") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planC_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
if ($plan = "planA1") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planA1_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
else {
echo "<p style='color:red'>User not found...</p>";
}
?>
The Problem is with the If condition: The Url's that needs to be displayed on my index page should change according to the $plan variable. But for some reason the $plan variable is always planA..
There are 4/5 Plans.. planA, planB, planc, planA1 each having different Urls that needs to displayed.
The URL do get populated but will be always the First IF conditions URL for all the customers.
Please help me out with this. Stuck for big time.
-------Update-------------
I want each of the Receive Payment to be according to the if conditions.. Now its all only planA
Here i am using php pdo for perform the search task.
i am create a two file 'search.php' is a send ajax request to query.php file.
search.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
<!-- jQuery cdn link -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</head>
<body>
<input type="text" id="search" placeholder="Search">
<div class="table-div" style="display: none"></div>
</body>
</html>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
$.get("/query.php", {data:$(this).val()}, function(data, status){
let row = JSON.parse(data);
let table = "";
table += "<table>";
table += "<thead>";
table += "<tr>";
table += "<th>Customer name</th><th>Customer salary</th>";
table += "</tr>";
table += "</thead>";
table += "<tbody>";
if(row.data != "No data found") {
$.each(row.data, function(key, value){
table += "<tr>";
table += "<td>"+ value.customer_name +"</td>";
table += "<td>"+ value.cust_sal +"</td>";
table += "</tr>";
});
}
table += "</tbody>";
table += "</table>";
$(".table-div").html(table);
$(".table-div").show();
});
});
});
</script>
query.php
<?php
// This is a database connectivity
$conn = new PDO("mysql:host=localhost; dbname=test;", 'root', '');
if(isset($_GET['data']))
{
$query = "%".$_GET['data']."%";
$searchSQL = "SELECT * FROM cust WHERE customer_name LIKE :cname";
$searchState = $conn->prepare($searchSQL);
$searchState->bindParam(":cname", $query);
if($searchState->execute())
{
if($searchState->rowCount() > 0)
{
$data = $searchState->fetchAll();
}
else
{
$data = "No data found";
}
}
echo json_encode(["data" => $data]);
}
?>
Hmm you said you tried == it should be == and not =.
Firstly please note your sql queries any kind of query should be prepare statements even if you trust your users.
Now please note that:
echo "planA"=="plana" ? "yes" : "no"; // Output no. Have you tried this?
Edit: I overlooked " But for some reason the $plan variable is always planA.." that is because of = in your ifs
$plan = "";
if ($plan = "a") {
echo $plan;
}
if ($plan = "b") {
echo $plan;
}
if ($plan = "c") {
echo $plan;
}
//output: abc
Lastly, please use else if, you don't need to check if 3 times it can only be 1 option.
Edit 2: I think you have some way to go. Please have look at the code below.
Here is the complete working with your bug I think:
<?php
// Since I have no post i will set it by default
$_POST['query'] = 'AZ12';
// Check for data validation...
if (!isset($_POST['query']) || empty($_POST['query'])) return;
// Now for query
$query = "SELECT * FROM `create_customer` WHERE `Customer Id` LIKE ? LIMIT 6";
// Prepare the statement to insert user_answer in ? above
// replace "s" based on your appropriate var type
$stmt = $conn->prepare($query);
// $stmt->bind_param("s", "%".$_POST['query']."%"); <-- This would yield error
// ^ fix: Store the 2nd param first
$like = "%{$_POST['query']}%";
$stmt->bind_param("s", $like);
$stmt->execute();
// Get the results
$result = $stmt->get_result();
echo "<br/>";
print_r($result);
// Output: mysqli_result Object ( [current_field] => 0 [field_count] => 3 [lengths] => [num_rows] => 1 [type] => 0 )
// ^ This will show all the elements part of $result (your case 6)
// Why this? Because to me it seems like you have hard-coded plans
// because if $plan = A,B,C and then you insert while loop inside the if's
$plans = array(0 => 'PlanA', 1 => 'PlanB', 2 => 'PlanC');
foreach($plans as $value) {
echo "<h1>$value</h1><br/>";
// Now loop as assoc like you have...
while ($row = $result->fetch_assoc()) {
print_r($row);
// ^ With above get the data value you need such as:
// echo "<h2>".$row['Customer Id']."</h2>";
}
// Add this to fix the fetch_assoc
$result->data_seek(0); // without this you will see the image below
}
// ^ Output Notice we only show plan A rows!!! look image below.
// Fix indicate by $result->data_seek(0);
?>
I am assuming this is what you get: "Why only A show?"
Once we click on Download button, we are trying to download complete order details in pdf.... here 100452121 is orderid, xpress is shipping name & 14104918100111 is tracking id....
we set conditions that if tracking_id is empty, than it should echo 0 but we are getting zero [0] even when tracking_id available for the order....
Shippinglabel.php Full code in pastebin
<td><?php echo $orderrecords[$k]["order_id"]; ?><br/>
<?php
if ($st == 1) {
if ($orderrecords[$k]["tracking_id"] == '') {
?>
<input type="button" name="shipment" id="xpress" value="xpress"
onclick="createshipment('<?php echo $orderrecords[$k]["order_id"];?>')" />
<?php
}
}
?>
<?php
if ($orderrecords[$k]["tracking_id"] != '' && $orderrecords[$k]["shipping_name"] == 'xpress')
{
?>
<a target="_blank"
href="http://sbdev1.kidsdial.com/ecom1/xpress/xpressdownload.php?orderId=<?php
echo $orderrecords[$k]["order_id"];?>"
id="pdfdownload" >
<input type="button" name="shipment" value="DOWNLOAD" /></a>
<?php
}
?>
</td>
createshipment
function createshipment(orderid)
{
var assignee='<?php echo $_SESSION['login_user']?>';
alert(orderid);
$.ajax({
url: "xpressshipment.php",
type: "POST",
data:'orderid='+orderid+'&assignee='+assignee,
success: function(data){
if(data==1)
{
$("#pdfdownload").show();
}
if(data==0){alert("First Enter Tracking Id.");}
window.location ="http://sbdev1.kidsdial.com/ecom1/xpress/xpressdownload.php?orderId="+orderid;
}
});
}
xpressshipment.php Full code in pastebin
<?php
$data =
array (
'AirWayBillNO' => $resultc[0]['awb'],
);
if($res->AddManifestDetails[0]->ReturnMessage=='successful')
{
$sqli="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress' where order_id='".$order_id."'";
$resulti=$db_handle->executeUpdate($sqli);
}
?>
xpressdownload.php Full code in pastebin
<?php
if(isset($_GET['orderId']) && $_GET['orderId']!='')
{
$orderid=$_GET['orderId'];
}
else
{
echo 2;
}
$orderid='';
$sqlorder = "SELECT tracking_id,order_id from do_order where order_id='".$orderid."' limit 1";
$resultdoorder = $db_handle->runSelectQuerys($sqlorder);
if($resultdoorder['tracking_id']=='')
{
echo 0;
//var_dump("tracking_id");
}
var_dump("tracking_id"); gave string(11) "tracking_id" as result....
please let me know if you need more details....
please help me to find solution....
Thanks in Advance....
In file xpressdownload.php you defined variable $orderid incorrectly.
if(isset($_GET['orderId']) && $_GET['orderId']!='')
{
$orderid=$_GET['orderId'];
}
else
{
echo 2;
}
$orderid='';
First, you are checking whether $_GET['orderId'] exists and if yes, you give the value of $_GET['orderId'] to $orderid. This is correct.
But after the if... else block you give the $orderid the '' value. So in every case the $orderid has the null value and you sql query is not returning the record. You have to remove the line $orderid=''; or move it before the if statement.
I am looking for some initial direction on this one because I cannot seem to find my way with it. Let me explain... I'm creating a music website and having a search bar. It filters information as the user types. I don't want to make a separate .php file for each song on the website. (Eg: song1.php, song2.php, etc...). There should be one PHP template file, that outputs the webpage for ALL songs. With my code, when I try searching with the search bar, it opens the template file as expected but it fills the file with information of only the first row from the mysql table. This is the form, its in the index page:
<script type = "text/javascript "src = "jquery.js">
<form class="navbar-form navbar-left" >
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search for songs, artists" autocomplete="off">
<div id = "searchresults"> </div>
Then there's the search.js file having two tasks, that is to check if a result has been clicked and also if the user has pressed a key. Its like this:
$('#search').keyup(function()
{
var searchterm = $ ('#search').val();
if (searchterm != '')
{
$.post('search.php', {searchterm:searchterm},
function(data)
{
$('#searchresults').html(data);
});
}
else{
$('#searchresults').html('');
}
});
$('#mylink').click(function(){
var wanted = $('#mylink').val();
$.post('/web/ztemplate.php', {wanted:wanted});
});
I think it's the one having an error but I can't figure out where it is. The template file has this php code :
$search = $_POST['wanted'];
$find = mysql_query("SELECT * FROM search WHERE title LIKE '%$search%'");
$row = mysql_fetch_assoc($find); $title = $row["title"];
There's a search.php file which queries the database to provide information for the instant search. It looks like this :
$search = mysql_real_escape_string(trim($_POST['searchterm']));
if ($search == '' && ' '){
echo 'No results found';
}
else {
$find_videos = mysql_query("SELECT * FROM search WHERE keywords LIKE '%$search%'");
$count = mysql_num_rows($find_videos);
if ($count ==0){
echo 'No Results found for '.$search;
}
else {
while($row = mysql_fetch_assoc($find_videos)){
$title = $row["title"];
$link = $row["link"];
echo "<a href = '$link'><h5 id = 'mylink'> $title <h5> </a> <hr /> ";
}
}
}
Any help is much appreciated.
why you not send an AJAX??
$('#search').keyup(function(){
var searchterm = $ ('#search').val();
if (searchterm != ''){
$.ajax({
type: 'POST',
data: {
"searchterm": searchterm,
"_token":"{{ csrf_token() }}"
},
url: "{{URL::asset('yourPHP')}}",
success: function(response){
$('#searchresults').html(response);
}
});
}else{
$('#searchresults').html('');
}
});
PHP
function searchSong($search =''){
$search = (trim($_POST['searchterm']));
$out='';
if ($search == '' && ' '){
echo 'No results found';
}else {
$sql = "SELECT * FROM search WHERE title LIKE '%$search%'";
$data= DB::select($sql);
$count = count($data);
if ($count ==0){
echo 'No Results found for '.$search;
}else {
foreach ($data as $key => $row) {
$title = $row["title"];
$link = $row["link"];
$out .= "<a href = '$link'><h5 id = 'mylink'> $title </h5> </a> <hr /> ";
}
}
}
return $out;
}
I have jQuery ListView that loads data from a php file. I also have a checkbox that onclick should be able to filter the list. The filtering is done by sending a post message to server and refreshing the list. However, the checkbox list is not filtering the list. The code below is only part of the whole implementation. Here is the page:
http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/restaurant_list.html
This is the HTML implementation:
<head>
<script>
lastRecord=0;
function loadRest(){
$('#sample').html( 'hello' );
$.get(
"queryRestaurantsList.php?lastRecord="+lastRecord,
function( data ) {
$('#rest_mesgs').append( data )
.listview( 'refresh' );
}
);
}
</script>
</head>
<body onload="loadRest()">
<div data-demo-html="true">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Select your type of Restaurant:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onchange="onfilter()" value="Vegetarian"/>
<label for="checkbox-h-2a">Vegetarian</label>
</fieldset>
</form>
</div>
<div data-demo-html="true">
<ul data-role="listview" data-theme="a" data-split-theme="b" data-split-icon="plus" data-inset="true" id="rest_mesgs">
<li data-role="list-divider">Restaurants</li>
</ul>
</div>
<script>
function onfilter(){
if($("#checkbox-h-2a").prop('checked')){
document.getElementById("hehe").innerHTML = "if condition is true";
var a = document.getElementById("checkbox-h-2a");
$.post("queryRestaurantsList.php",
{
filter0 : a.value;
},
function(data){
$('#rest_mesgs').append( data )
.listview( 'refresh' );
});
}
else {
document.getElementById("hehe").innerHTML = "not working";
}
}
</script>
</body>
This is php file:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
//Check if POST array is empty or not
if ($_POST == null){
$query = "SELECT Name,Short_Loc,Image_Link,Type FROM Restaurant_Info";
$result = mysql_query($query) or die( "Unable to execute query");
while ($row = mysql_fetch_array($result)){
print '<li>';
print '<a href="'.$row['Full_Link'].'">';
print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
print '<h2 style="text-wrap : normal">'.$row['Name'].'</h2>';
print '<p id="type" class="ui-li-aside"><strong>'.$row['Type'].'</strong></p>';
print '<p>'.$row['Short_Loc'].'</p>';
print '</a>';
print '</li>';
}
}
else {
$value1 = $_POST[filter0];
$query0 = 'SELECT Name,Short_Loc,Image_Link FROM Restaurant_Info WHERE Type LIKE ';
$query0 = $query0.'"%'.$value1.'%"';
$result = mysql_query($query0) or die( "Unable to execute query");
$num_results = mysql_num_rows($result);
if ($num_results == 0){
print "Your criteria does not match any of the restaurants";
}
else{
while($row = mysql_fetch_array($result)) {
print '<li>';
print '<a href="'.$row['Full_Link'].'">';
print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
print '<h2 style="text-wrap : normal">'.$row['Name'].'</h2>';
print '<p>'.$row['Short_Loc'].'</p>';
print '</a>';
print '</li>';
}
}
I can see 2 errors, but unfortunately I can't test them.
1 - This php part:
else {
$value1 = $_POST[filter0];
Should be replace with:
else {
$value1 = $_POST['filter0'];
Otherwise filter0 will be treated as a constant instead of a string.
2 - On your html, you did:
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onchange="onfilter()" value="Vegetarian"/>
This should be
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onclick="onfilter()" value="Vegetarian"/>
I think a checkbox won't fire onchange when you check or uncheck it.
1 . To maintain checkbox state change use jQuery.toggle(). It's the safest way.
$("#checkbox-h-2a").toggle(function(){
var filter = $(this).val();
getListviewItems({filter0: filter});
}, function() {
getListviewItems();
});
2 . Make one function with params for getting list items. That way you'll keep your code clean and easy to maintain.
function getListviewItems(opt) {
opt.filter0 = (opt.filter0 == undefined)?'':opt.filter0;
/* Body of function, post and/or get calls, etc. */
}
how can I get the variable value I need, I have selected comments and like values through MySQL and have created a like button, but when I click like, it adds the like to the last selected/posted variable value, so it likes the last comment generated. How to I get it to like the one I wanted and not the last selected?
Example:
I have comments with id's (1,2,3) when generated it orders them in that order (1,2,3) when I like comment with id=2 it likes comment 3 because it was last generated so the varible id has a value of 3 at the time I liked comment 2.
I don't make any sense, I hope you guys get it, please help???
Let's say we have three comments all on the same post:
First Table: comments
id | post_id | comment
1 | 1 | "something"
2 | 1 | "something else"
3 | 1 | "something else entirely"
Second Table: comment_likes
id | comment_id
1 | 2
2 | 2
3 | 3
In this example, comment 2 would have 2 likes, and comment 3 one.
This might be the code to show our comments. The trick here is to add a custom attribute to the like link so we can detect the comment id in javascript.
<div class="comments">
<?php
$res = mysql_query('SELECT * FROM `comments` WHERE `post_id` = '.$post_id.';');
while ($row = mysql_fetch_array($res)) {
$cid = $row['id'];
echo '<div class="comment">';
echo $row['comment'].'<br />';
echo '<span class="like" comment-id="'.$cid.'">Like</span>';
$lres = mysql_query('SELECT COUNT(*) FROM `comment_likes` WHERE `comment_id` = '.$cid.';');
$likes = mysql_result($lres,0);
echo '<span class="likes">';
if ($likes > 0) {
echo '<span class="num_likes">'.$likes.'</span>';
$p = ($likes > 1) ? 'people like' : 'person likes';
echo $likes.' '.$p.' this';
}
echo '</span>';
echo '</div>';
}
?>
</div>
Now the JavaScript (using jQuery):
$(document).ready(function() {
$('.like').click(function() {
var id = $(this).attr('comment-id');
$.ajax({
url: 'add_like.php',
method: 'POST',
data: {'id':id},
success: function(res) {
if (res === '1') {
var likes = $('.like[comment-id='+id+']').find('.num_likes').text();
likes++;
var p = likes > 1 ? 'people like' : 'person likes';
var html = '<span class="num_likes">'+likes+'</span> '+p+' this';
$('.like[comment-id='+id+']').find('likes').html(html);
}
else alert('Error Liking Comment');
},
error: function() { alert('Error liking comment'); }
});
});
});
And the PHP (for the AJAX) - add_like.php
<?php
if (!isset($_POST['id'])) exit;
$id = $_POST['id'];
// connect / select db
$res = mysql_query('INSERT INTO `comment_likes` WHERE `comment_id` = '.$id.';');
if ($res) {
die(1); // success
}
die(0);
?>
Obviously you'd want to expand this for liking/un-liking - because at the moment the user can like multiple times but you get the idea.
note.php
//-------- WHILE LOOP FOR GETTING NOTE COMMENTS -------
$commentsList = array();
$query = mysql_query("SELECT * FROM note_comments WHERE note_id='$note_id'");
while (($row = mysql_fetch_assoc($query)) != false) {
$commentsList[] = array(
'comId' => $row['id'],
'comment' => $row['comment'],
'com_likes' => $row['likes'],
'com_likers' => $row['likers']
);
}
note.php (body):
<div id="noteComments">
<h2>Comments</h2>
<?php
$commentL = $commentsList;
if (count($commentL) == 0) {
echo 'Sorry, there are no comments.';
} else {
echo '<ul style="list-style:none;">';
foreach($commentL as $comment) {
echo '<li><p>', $comment['comment'], '</p><p><a style="background-color:#3b3c3b; color:#fff;
text-decoration:none; padding: 1 5 1 5; border-radius:5px; border: 1px solid black; " href="#" onclick="like_add(', $comment['comId'] ,');">Like</a><span id="comment_', $comment['comId'] ,'_likes">', $comment['com_likes'] , '</span> like this</p></li>';
}
echo '</ul>';
}
?>
</div><!-- end noteComments -->
like.js
function like_add(comId) {
$.post('ajax/like_add.php', {comId:comId}, function(data) {
if (data == 'success') {
like_get(comId);
} else {
alert(data);
}
});
}
function like_get(comId) {
$.post('ajax/like_get.php', {comId:comId}, function(data) {
$('#comment_'+comId+'_likes').text(data);
});
}
like_add.php
<?php
include_once("../scripts/checkuserlog.php");
include '../functions/like.php';
if (isset($_POST['comId']) && comment_exists($_POST['comId'])) {
$comId = $_POST['comId'];
add_like($comId);
}
?>
like_get.php
<?php
include '../scripts/checkuserlog.php';
include '../functions/like.php';
if (isset($_POST['comId']) && comment_exists($_POST['comId'])) {
echo like_count($_POST['comId']);
}
?>
like.php
<?php
function comment_exists($comId) {
$comId = (int)$comId;
return (mysql_result(mysql_query("SELECT COUNT('id') FROM note_comments WHERE id=$comId"), 0) == 0) ? false : true;
}
function like_count($comId) {
$comId = (int)$comId;
return (int)mysql_result(mysql_query("SELECT likes FROM note_comments WHERE id=$comId"), 0, 'likes');
}
function add_like($comId) {
$comId = (int)$comId;
$visitor = $_SESSION['id'];
$com_likers = "";
$query = mysql_query("SELECT likes, likers FROM note_comments WHERE id='$comId'");
while (($row = mysql_fetch_array($query)) != false) {
$com_likes = $row['likes'];
$com_likers = $row['likers'];
}
$thisComlikers = explode(",", $com_likers);
if (!in_array($visitor, $thisComlikers)) {
if ($com_likers != "") { $com_likers = "$com_likers,$visitor"; } else { $com_likers = "$visitor"; }
mysql_query("UPDATE note_comments SET likes = likes + 1 WHERE id=$comId")or die (mysql_error());
mysql_query("UPDATE note_comments SET likers =$com_likers WHERE id=$comId")or die (mysql_error());
echo 'success';
} else {
echo 'You have already liked this!';
}
}
?>