2017-07-07 103 views
1

我有一个HTML脚本,其中包含一个表单,此表单将一个Name值提交给一个PHP脚本。在这个PHP脚本中,我打开两个不同的文本文件,第一个文件是获取内部数字,然后将其增加1.另一个文件将打开,然后将新递增的数字与Post中的Name值一起写入。 其中只有一个数字的第一个文件开始在“0”,这是我有问题的地方。当运行代码时,什么都不会发生,表单被完美地提交并调用PHP脚本。但是两个不同文本文件中唯一的值是“0”。相反,它应该在“amount.txt”文件中有“1”,在“textContent.txt”文件中应该有“Text to appear:1 Other text:Name”。在一个文本文件中增加值并将文本写入另一个

我不完全确定我错在哪里,对我来说这似乎理论上是正确的。

下面是PHP部分,这是不工作的部分。

$nam = $_POST['Name']; 

$pastAmount = (int)file_get_contents('/user/site/amount.txt'); 
$fileOpen1 = '/user/site/amount.txt'; 
$newAmount = $pastAmount++; 
file_put_contents($fileOpen1, $newAmount); 

$fileOpen2 = '/user/site/textContent.txt'; 

$fileWrite2 = fopen($fileOpen2 , 'a'); 
$ordTxt = 'Text to appear: ' + $newAmount + 'Other text: ' + $nam; 
fwrite($fileWrite2, $ordTxt . PHP_EOL); 
fclose($fileWrite2); 
+0

是不是连接操作符 ''而不是'+'? --- $ ordTxt ='要显示的文本:'+ $ newAmount +'其他文本:'+ $ nam; – Khan

+0

@Khan是的,我刚才知道了,我的错误。谢谢。 – DevLiv

回答

1

相反的:

$newAmount = $pastAmount++; 

你应该使用:

$newAmount = $pastAmount + 1; 

因为$ pastAmount ++会直接更改$ pastAmount的值。

然后,而不是

$ordTxt = 'Text to appear: ' + $newAmount + 'Other text: ' + $nam; 

你应该使用:

$ordTxt = 'Text to appear: '.$newAmount.' Other text: '.$nam; 

因为在PHP中,我们使用的是。用于连接。

PHP代码:

<?php 
$nam = $_POST['Name']; 


// Read the value in the file amount 
$filename = "./amount.txt"; 
$file = fopen($filename, "r"); 
$pastAmount = fread($file, filesize($filename)); 
$newAmount = $pastAmount + 1; 
echo "Past amount: ".$pastAmount."-----New amount:".$newAmount; 
fclose($file); 

// Write the value in the file amount 
$file = fopen($filename, "w+"); 
fwrite($file, $newAmount); 
fclose($file); 


// Write your second file 
$fileOpen2 = './textContent.txt'; 
$fileWrite2 = fopen($fileOpen2 , 'w+ '); 
$ordTxt = 'Text to appear: '.$newAmount.' Other text: '.$nam; 
fwrite($fileWrite2, $ordTxt . PHP_EOL); 
fclose($fileWrite2); 
?> 
+1

非常感谢你的答案,它现在正在工作,我想如何。 – DevLiv

1

首先,错误在你的代码:

  1. $newAmount = $pastAmount++; =>这将分配$pastAmount的值,然后增加它不是你瞄准什么样的价值。
  2. $ordTxt = 'Text to appear: ' + $newAmount + 'Other text: ' + $nam; =在PHP>级联与.而不是+

正确的代码完成:

$nam = $_POST['Name']; 

$pastAmount = (int)file_get_contents('/user/site/amount.txt'); 
$fileOpen1 = '/user/site/amount.txt'; 
$newAmount = $pastAmount + 1; 
// or 
// $newAmount = ++$pastAmount; 

file_put_contents($fileOpen1, $newAmount); 

$fileOpen2 = '/user/site/textContent.txt'; 

$fileWrite2 = fopen($fileOpen2 , 'a'); 
$ordTxt = 'Text to appear: ' . $newAmount . 'Other text: ' . $nam; 
fwrite($fileWrite2, $ordTxt . PHP_EOL); 
fclose($fileWrite2); 
+0

您的回答非常感谢,谢谢。 – DevLiv

相关问题