在PHP中简单的点击计数器的麻烦

时间:2014-08-31 18:19:09

标签: php mysql

我正在拼凑一个非常简单的PHP脚本,但我无法让它工作。我正在连接到SQL数据库,但它没有检索我想要的值。我只在一个数据库的单个表中有一个条目。我想检索该值,然后添加一个值。

    <?php 
        $dbhost = 'localhost'; 
        $dbuser = 'root'; 
        $dbpass = 'root'; 
        $dbname = 'test'; 
        $dbtable = 'counter'; 

        //------ DATABASE CONNECTION --------// 
        mysql_connect($dbhost,$dbuser,$dbpass) 
        or die ("Unable to connect to database"); 

        mysql_select_db($dbname) 
        or die ("Unable to select database"); 

        $test = "SELECT FIRST('count') FROM $dbtable";

    ?> 

    This button has been clicked <?php echo $test; ?> times.

编辑:借助angelo

找到解决方案
    <?php 
    //parameters to set
    $dbhost = 'localhost'; 
    $dbuser = 'root'; 
    $dbpass = 'root'; 
    $dbname = 'test'; 
    $dbtable = 'counter'; 
    $dbcolumn = 'count';
    //end of list of parameters to set
    $connect = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
    if(!$connect){die("Connection error");}
    $test = mysqli_query($connect,"SELECT ".$dbcolumn." FROM ".$dbtable);
    $assoc = mysqli_fetch_assoc($test);
    $num = $assoc[$dbcolumn];


?> 

This button has been clicked <?php echo $num; ?> times.

<?php

    $plus = $num+1;
    //mysqli_query($connect,"INSERT INTO ".$dbtable."('".$dbcolumn."') VALUES ('".$plus."')");
    mysqli_query($connect,"DELETE FROM counter WHERE count = $num");
    mysqli_query($connect,"INSERT INTO counter (count) VALUES ($plus)");

?>

1 个答案:

答案 0 :(得分:2)

为什么你的代码不能正常工作

您未启动查询

警告

您正在使用不推荐使用的mysql_函数。你应该使用mysqli_代替。

解决方案

使用此代码:

 <?php 
        //parameters to set
        $dbhost = 'localhost'; 
        $dbuser = 'root'; 
        $dbpass = 'root'; 
        $dbname = 'test'; 
        $dbtable = 'counter'; 
        $dbcolumn = 'col';
        //end of list of parameters to set
        $connect = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
        if(!$connect){die("Connection error");}
        $test = mysqli_query($connect,"SELECT ".$dbcolumn." FROM ".$dbtable);
        $assoc = mysqli_fetch_assoc($test);
        $num = $assoc[$dbcolumn];
        ?> 

    This button has been clicked <?php echo $num; ?> times.

请注意,此代码仅显示点击次数。 要为此值添加1,请将以下代码附加到上一个代码:

<?php
$plus = $num+1;
$query = "UPDATE ".$dbtable." SET ".$dbcolumn."='".$plus."'";
mysqli_query($connect,$query);
?>