我正在拼凑一个非常简单的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)");
?>
答案 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);
?>