Firing SQL query on click of button?

2019-03-05 11:56发布

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条回答
Evening l夕情丶
2楼-- · 2019-03-05 12:31

Option#1 (Easy):

Reload the page on clicking the button:

<span id="button" onclick="javascript: location.reload();">Click Me</span>

Option#2:

  1. Put the query portion in separate file (say inc.php)
  2. 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>
查看更多
登录 后发表回答