问题
I have a simple PHP/MySQL counter which incrementally increases a value in my SQL database. Currently, this script fires every time the page refreshes meaning that the number increases by 1 every time the page is refreshed. I would like to change it so that it only increases when a button is pressed.
Here is my PHP code:
<?php
error_reporting(0);
include("config.php");
// get click details based on ID
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE id='1'";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
$sql = "UPDATE ".$SETTINGS["data_table"]." SET clicks=clicks+1 WHERE id='1'";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
?>
And here is the button I would like to tie it to:
<div class="content">
<span id="button">Click Me</span>
</div>
Any ideas on how I can accomplish this? Thanks!
回答1:
Option#1 (Easy):
Reload the page on clicking the button:
<span id="button" onclick="javascript: location.reload();">Click Me</span>
Option#2:
- Put the query portion in separate file (say inc.php)
- Use an AJAX call on the onclick event of the button span. (You can use JQuery)
Here is an example with jQuery AJAX:
<script type="text/javascript">
<!--
function inc_counter()
{
$.ajax({
url: "inc.php",
context: document.body
}).done(function() {
alert('incremented');
});
return false;
}
-->
</script>
<span id="button" onclick="javascript:return inc_counter();">Click Me</span>
来源:https://stackoverflow.com/questions/20410545/firing-sql-query-on-click-of-button