1

单击按钮时,我似乎找不到增加存储在 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";     ?>


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

4

3 回答 3

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';   ?>

根据您的需要进行修改

于 2013-06-27T11:58:02.837 回答
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;
?>
于 2013-06-27T11:54:32.527 回答
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'");
于 2013-06-27T12:01:59.860 回答