I'm basically working on a site in which a user repeatedly clicks a button, increasing his score each time he clicks. I don't want the page to refresh between each click, so I'm using AJAX.
The problems I'm having currently are as follows:
When I try to set my javascript
var
to=
<? echo $result['count']; ?>
, it doesn't seem to work.I don't understand how to correctly use PDO to
UPDATE
a MySQL table with a calculation in the query, such as$update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");
. Is this the correct syntax for the calculation and is this the right way to do it in PDO?
Here is the code for my testing page which I am using for the clicking system:
<html>
<?php
$hostname = 'localhost';
$username2 = 'refrigerator';
$password = 'xxx';
$dbh = new PDO("mysql:host=$hostname;dbname=refrigerator", $username2, $password);
$username = $_COOKIE["user"];
$rows = $dbh->prepare("SELECT count FROM count WHERE username = '$username'");
$rows->execute();
$result = $rows->fetchALL();
$result['count'] = $count;
if(isset($_POST['action'])){
if ($_POST['action'] == 'increase'){
$update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");
开发者_高级运维 }
}
?>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var count = <? echo $result['count']; ?>;
$("#update").click(function() {
$.ajax({
type: "POST",
url: "button.php",
data: {"action":"increase"},
success: function(update) {
count++;
$("#counter").html(+count);
}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"><? echo $result['count']; ?></div>
</body>
</html>
Thanks a lot, any help would be greatly appreciated. Even if you can point me in the right direction which will help me answer my questions, that would be awesome.
Thank you
You should have:
$count = $result['count'];
Instead of:
$result['count'] = $count;
The variable to the left of the = sign is what is receiving the assignment from whatever value is on the right of the = sign.
In your update statement you could, instead of using your count variable, could do:
$update = $dbh->execute("UPDATE count SET count=count+1 WHERE username='$username'");
精彩评论