2016-08-17 158 views
1

我有一个脚本,当某个按钮被按下时,它将+1或-1加到变量上。 “+1”按钮可以很好地工作,但当变量的值为“10”时(也可能是其他值),“-1”按钮会变为奇数。当我点击按钮时,不显示“9”,而是显示“90”。计算按钮点击次数的PHP脚本

PHP:

<?php 
$myfile = fopen("response.txt", "r+") or die("Unable to open file!"); 
$currentvalue = file_get_contents("response.txt"); 
$currentvalue = $currentvalue -1; 
fwrite($myfile, $currentvalue); 
fclose($myfile); 
header('Location: otherfile.php') ; 
?> 

HTML

<form method="post" action="minus.php"> 
<button> Remove one </button> 
</form> 

我知道有这项任务更好的方法,但上面的代码是我能想出,考虑到我的基本知识最好PHP。

谢谢。

回答

1

发生这种情况是因为您在r+模式下打开文件。这不会截断文件,因此当您写入“9”时,将覆盖“10”中的“1”,而该文件中的第二个字符仍然为“0”。这给你“90”。

通过不使用fopen,fwritefclose解决此问题:删除这些语句。而是用file_put_contents写出结果:

$currentvalue = file_get_contents("response.txt"); 
$currentvalue = $currentvalue - 1; 
file_put_contents("response.txt", $currentvalue); 
+0

感谢您的快速响应,它的工作原理。 – C10H15N