增加一个文本文件中的值并将文本写入另一个文件

Increment value in one text file and write text to another

我有一个 HTML 脚本,其中包含一个表单,此表单将名称值提交给 PHP 脚本。在这个 PHP 脚本中,我打开了两个不同的文本文件,第一个文件是获取其中的数字,然后将其递增 1。另一个文件是打开,然后写入新递增的数字以及来自Post。 第一个文件里面只有一个数字,从“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);

首先,您的代码中存在错误:

  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);

而不是:

$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);
?>