I've made a 'like' button for my product pages with this code:
<?php
if('POST' == $_SERVER['REQUEST_METHOD']) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" value = "like"/>
</form>
Works like a charm excpet for one minor problem being that every visit to the page registers a 'like'.
Could someone help explain what i need to chnage/add in order that new 'likes' are only registered when the actual form is submitted?
Thanks
Dan
A better solution rather than submitting the page and the whole page reloading would be to make an AJAX request, this is how Facebook 'likes' work.
This can be achieved using the jQuery JavaScript library.
The general outline would be:-
1) Click button
2) Send AJAX request
3) Update HTML to show button has been clicked and prevent reclicking of button.
<?php
if($_POST['like']) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" value = "like" name='like'/>
</form>
This should work ;-)
<?php
if ($_POST['like']){
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" name="like" value = "like"/>
</form>
First of all - in your sql you have:
`product_id` = '1'
do not use id value as a string:
`product_id` = 1
About your problem:
Add another condition:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
if ( !empty($_POST['submitType']) && ( $_POST['submitType'] == 'like' ) ) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
}
and in html:
<input type = "submit" name="submitType" value = "like"/>
Sounds like some kind of old question, but I wonder why noone has said, that op's approach doesn't sound quite right. You try to just count likes (set likes=likes+1). It has many disadvantages:
You miss information, who gave the like. Thus you won't be able to reconstruct the whole picture
Users won't be able to "undo" likes (as you don't record who liked the post)
In case of many concurrent likes I feel like you'd get some kind of data race or a long delays, because MySQL would need to process every request on a single field in order.
Much better idea is to create separate table in the DB named "product_likes" with columns like product_id, user_id, date. Of course, product id and user id should be unique together.
Thus you'll always know the full picture and will be able to see who liked the product. Even if accidentally you'll issue the second like from the same user about the same product, it won't be stored due to db constraints.
Also it will be possible to extend it to i.e. emotions-reactions, just by adding new column like "like_type" and updating the constraint correspondingly.
Related
I want to increment the number of likes on a post (say for postid 109) whenever I click Like.
I added a new column likecount and all values are 0 by default. They do not increment on clicking Like button.
I've tried a lot and searched for similar questions, but to no help.
HTML
<form method= POST >
<input type=submit value='' name=like class=likebutton>
</form>
PHP
if($_POST['like']) {
$sqlst = "UPDATE images SET `likecount` = `likecount`+1 WHERE `postid` = '109'";
$rslt= mysqli_query($db2, $sqlst);
}
I think query is failing because postid is integer and you are adding string value. Also use isset() for checking $_POST['like'], isset will execute script only when $_POST['like'] not empty Kindly try following
if(isset($_POST['like'])) {
$sqlst = "UPDATE images SET `likecount` = likecount + 1 WHERE `postid` = 109";
$rslt= mysqli_query($db2, $sqlst);
}
You can try
if(isset($_POST["like"]))
instead of
if($_POST['like'])
I have been having an issue selecting data from my database based on the user id column. I know that I have to make use of PHP sessions to enable each user see their profile when they login, but I haven't been able to work out the code for this.
Here is what I have so far:
<?php session_start(); include 'dpconfig.php'; $id = $_SESSION['uid'] ?>
<?php
$run = mysqli_query($conn,"Select * from user Where first = '$id'");
$row = mysqli_fetch_array($run, MYSQLI_BOTH); {}
$showid = $row[0];
$showfirst = $row[1];
$showlast = $row[2];
echo $showid;
echo $showfirst;
echo $showlast;
?>
If I run the above code I get nothing echoed out, but if I remove the WHERE clause from my SELECT statement, all logged in users see the first column of my database.
I want each user to see their own profile, I learnt that I need to authenticate session, and I am confused. Please help.
Assumptions
I'm assuming your database has three columns, uid (the id of a user, int, primary key, auto_increment), first (the user's first name, varchar) and last (the user's last name, varchar).
I'm also assuming that when the user logs in, $_SESSION["UID"] is set to the value of the id column in their row.
Solution
As far as I can see, your WHERE clause is wrong. You wrote
Select * from user Where first = '$id'
which essentially means "Select everything from the user table where the first name is equal to the currently logged in user's id". I think you meant something more like
SELECT first, last FROM user WHERE uid='$id'
which means "Select the first and last names from the user table where the id is equal to the currently logged in user's id".
Code
I have re-written your PHP file, to make it a bit more readable and clear. You'll need to change the MySQL connection to whatever you were originally using, but apart from that, everything should work fine.
<?php
session_start();
require("dpconfig.php");
$q = "SELECT first, last FROM user WHERE uid='".$_SESSION["UID"]."'";
$r = mysqli_query($conn,$q);
$a = mysqli_fetch_assoc($r);
echo "First Name: ".$a["first"]."<br>";
echo "Last Name:".$a["last"];
?>
Second Question
For your form:
<form method="post" action="update.php">
<input type="text" name="status"><br>
<button>Submit</button>
</form>
For update.php:
<?php
session_start();
require("dpconfig.php");
if (isset($_POST["status"])) {
$q = "UPDATE user SET status='".addslashes($_POST["status"])."' WHERE uid='".$_SESSION["uid"]."'";
mysqli_query($conn,$q);
}
header("Location:./");
?>
I have the following code:
<iframe onscroll ="caise4.php" name="frame4"></iframe>
<input type= "submit" onclick ="frames['frame4'].print()" value = "WATER/ELECTRICITY" id = "id4"></a>
This would allow me to print a different page when the button/frame is clicked.
And i have the following PHP code:
<?php
if(isset($_POST['frame4'])){
$SQL_1 = "INSERT INTO `tick4` (`ticket_id`, `ticket_date`) VALUES (NULL, CURRENT_TIMESTAMP)";
$result_1 = mysqli_query($db, $SQL_1);
$SQL_2 = "UPDATE v_attente_service AS vas
JOIN (SELECT COUNT(ticket_id) AS cnt FROM tick4) AS ti
SET vas.NOMBATTE = ti.cnt
WHERE vas.CODESERV=4";
$result_2 = mysqli_query($db, $SQL_2);
}
?>
When the user clicks, a new row needs to be inserted in the table "tick4". Then "NOMBATTE" in "v_attente_service" is updated.
Basically, when the user prints a ticket, the number of tickets is updated, and the number of people waiting in the queue is also updated.
The problem I have: I get redirected to the page preview, but nothing is displayed there. Also, nothing gets updated in my tables.
I am using phpMyAdmin by the way.
Any help would be greatly appreciated. Thank you.
What I want to do is have a button allows that when clicked takes away 1 from the column 'tickets' in the table 'event' and adds it to the column 'ticket' in the table 'user'.
Code for button
form action="sendellie.php" method="post">
<input type="submit" value="Buy tickets"/>
</form>
Snippet of Code for processing page (sendellie.php)
<?php
$sql = "UPDATE event SET tickets = tickets-1 WHERE name='Ellie Goulding'";
$sql = "UPDATE user SET ticket = ticket+1 WHERE name = '$uname'";
?>
The problem with the code above is that it does not work. It does not take away or add anything.
Any suggestions or tips would be much appreciated. Thanks
I've got a bit of a strange situation, Im building a site to keep track of outgoings, on my website you can insert an infinite number of 'outgoings' or 'bills' into my table, this is done using AJAX.
Once inserted, the record then shows up on the page and the user has an option to update, or delete the record.
My problem, is that when the record is inserted and posted back, I don't know what ID the record has fr4om the table so the update function doesn't work correctly. I've tried adding a a hidden field 'random-key' that when the user inserts a record, a random number is inserted and the this is posted back for my update function only I cant seem to get it working.
Has anybody an idea on how best to perform this?
Thanks
My code...
PHP form
<form id='bill-upd'>
<input type='hidden' value='".$info['rand']."' name='rand2' id='rand2'>
<input type='hidden' value='".$info['id']."' name='billid' id='billid'>
Total <input type='text' id='total' name='total' /><br />
Bill name<input type='text' id='bill-name' name='bill-name' /><br />
Bill descriptiion <input type='text' id='bill-description' name='bill-description' /><br />
Bill colour<input type='text' id='bill-colour' name='bill-colour' />
<input type='button' value='submit' onClick='updateBill();' />
</form>
UPDATE PHP PAGE
$uid = $_SESSION['oauth_id'];
$id = mysql_real_escape_string($_POST['billid']);
$bill = mysql_real_escape_string($_POST['total']);
$billname = mysql_real_escape_string($_POST['bill-name']);
$billdescription = mysql_real_escape_string($_POST['bill-description']);
$billcolour = mysql_real_escape_string($_POST['bill-colour']);
$rand = mysql_real_escape_string($_POST['rand2']);
#update Record
$query = mysql_query("UPDATE `outgoings` SET id = '$id', user_id = '$uid', bill = '$bill', bill_name = '$billname', bill_description = '$billdescription', bill_colour = '$billcolour', rand = '$rand' WHERE user_id = '$uid' AND rand = '$rand' ") or die(mysql_error());
While Inserting the new record, Get the newly added id (assuming that you have a unique id for each record) from the table and return that as the part of result you are returning after your ajax call. Then you can use that id for updating the record.
You can use the below script to send the details to be updated to the update page
$("#bill-upd").submit(function(e){
e.preventDefault();
$.post("update.php",{
billid: $("#billid").val()
total: $("#total").val();
bill-name : $("#bill-name").val();
bill-description : $("#bill-description").val();
bill-color: $("#bill-color").val();
},
function(result){
//Update / Show a message to user about the action.
//alert(result);
});
});
});
And in your update.php page, change your query like this
$query = mysql_query("UPDATE `outgoings` user_id = '$uid', bill = '$bill', bill_name = '$billname', bill_description = '$billdescription', bill_colour = '$billcolour', rand = '$rand' WHERE id = '$uid' AND rand = '$id' ") or die(mysql_error());
Assuming ID is the unique id / Primary key in the table which we can use to update a table record.
When you use an INSERT query, you can use mysql_insert_id() to get the value of the AUTO_INCREMENT field created for the inserted row. You can send this back with JSON so Javascript knows the ID of your newly inserted row. However consider if another user (using a different browser) adds a row while another user has the page open, Javascript won't get the new row. Example:
User 1 loads page and sees no rows.
User 1 adds Row #1.
User 2 loads page and sees Row #1.
User 2 adds Row #2 and now sees Rows #1,2
User 1 adds Row #3, but only sees Rows #1,3
And now User 2 will only see rows #1,2
You should probably really be SELECT * from table after every query to make sure you have all rows (including the ones other users may have inserted). You should also consider using PDO.