单击按钮时mysql增加值

时间:2013-06-27 11:47:14

标签: php html mysql sql

单击按钮时,我似乎找不到增加存储在mysql数据库中的值的方法。

html中的按钮(不包括使用css的样式):

<a class="button">Press Me</a>


我的mysql数据库全部设置和工作,每次单击此按钮/链接时,我都找不到增加数据库值的方法。您应该可以多次单击此按钮而无需离开页面。

我尝试过使用PHP,但只会在页面加载后发送信息,这意味着没有点击按钮,而且我还没有找到一种方法来增加每次点击的价值。顺便说一句,这不一定要用PHP来完成。

<?php
// Connection to database
  $connection=mysqli_connect("localhost","root","","test");
// Check connection
  if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Increasing the current value with 1
  mysqli_query($connection,"UPDATE articles SET amount = (amount + 1)
      WHERE id='1'");

  mysqli_close($connection);

  echo "PHP RAN successfully";     ?>


* 另外,抱歉我的英语不好,我是瑞典人:)

3 个答案:

答案 0 :(得分:2)

在您的页面中包含jquery作为JS库。

<a class="button" id="press_me">Press Me</a>
<script>
    $(function (){
            $('#press_me').click(function(){
            var request = $.ajax({
                                    type: "POST",
                                    url: "server_code_increment.php"                               
                                  });
                                  request.done(function( msg ) {

                                        alert('Success');
                                        return;

                                  });
                                  request.fail(function(jqXHR, textStatus) {
                                        alert( "Request failed: " + textStatus );
                                    });
            });
    });
    </script>

server_code_increment.php

<?php
// Connection to database
  $connection=mysqli_connect("localhost","root","","test");
// Check connection
  if (mysqli_connect_errno())
    {
    echo 'NOT_OK';
    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Increasing the current value with 1
  mysqli_query($connection,"UPDATE articles SET amount = (amount + 1)
      WHERE id='1'");

  mysqli_close($connection);

  echo 'OK';   ?>

根据您的需要进行修改

答案 1 :(得分:0)

你不必使用ajax虽然它可能更漂亮。这将适用于基本的ahref重新加载页面

<a class="button" href="<?php echo $_SERVER['PHP_SELF'];?>&a=increase">Press Me</a>

<?php
if ($_GET['a']=="increase") {
// Connection to database
  $connection=mysqli_connect("localhost","root","","test");
// Check connection
  if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Increasing the current value with 1
  mysqli_query($connection,"UPDATE articles SET amount = (amount + 1)
      WHERE id='1'");

  mysqli_close($connection);

  echo "PHP RAN successfully";     
}

//echo out the DB value here
echo $db->amount;
?>

答案 2 :(得分:0)

 <a href="yourpage.php?id=1">Press me</a>

id(唯一的可用)

<? php
 $no=$_get['id'];
?>

从db

中选择您最后插入的数量
 eg: $lastamount=mysql_query("select query for last insertdata");
 write 
 $no=$lastamount+$no;
 mysqli_query($connection,"UPDATE articles SET amount = $no
  WHERE id='1'");