PHP/MySQL 喜欢按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7401141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP/MySQL Like Button
提问by Dan
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'.
对于一个小问题,每次访问页面都会记录一个“喜欢”,这就像一个魅力excpet。
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
谢谢丹
采纳答案by diagonalbatman
<?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 ;-)
这应该有效;-)
回答by Bruce
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.
比提交页面和整个页面重新加载更好的解决方案是发出 AJAX 请求,这就是 Facebook“喜欢”的工作方式。
This can be achieved using the jQueryJavaScript library.
这可以使用jQueryJavaScript 库来实现。
The general outline would be:-
一般大纲是:-
1) Click button
1)点击按钮
2) Send AJAX request
2) 发送 AJAX 请求
3) Update HTML to show button has been clicked and prevent reclicking of button.
3) 更新 HTML 以显示已单击的按钮并防止重新单击按钮。
回答by genesis
<?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>
回答by hsz
First of all - in your sql you have:
首先 - 在你的 sql 你有:
`product_id` = '1'
do not use id value as a string:
不要使用 id 值作为字符串:
`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:
并在 html 中:
<input type = "submit" name="submitType" value = "like"/>