Firing SQL query on click of button?

烈酒焚心 提交于 2019-12-02 15:03:52

问题


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:

  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>


来源:https://stackoverflow.com/questions/20410545/firing-sql-query-on-click-of-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!