0

我的网站上有一个联系表,在我的 PHP 中,我使用

$subject = $_POST['subject'];

将电子邮件的主题设置为用户在 name='subject' 字段中输入的内容。

有什么方法可以在主题末尾添加一个 ID,以便每封电子邮件的 ID 号 +1?

我猜 PHP 需要将它存储在某个地方才能知道最后一个 ID 号是什么,但我不确定如何执行此操作。

完成后,我收到的电子邮件将包含以下主题:

user2354 typed subject [ID:000001]
user3456 typed subject [ID:000002] 
(and so on ...)
4

2 回答 2

1

如果要使用文件来存储 id,可以使用这段代码:

<?php 

$filename = __DIR__.'/id.txt'; // The file

if(!file_exists($filename)) { // File not exist start at 0
    $id = 0;
}
else {
    $id = file_get_contents($filename); // Get the id from the file
}

$id++; // Increment the id

file_put_contents($filename, $id); // Put the new id in the file

// The subject of the message
$subject = $user.' typed subject '.$_POST['subject'].' [ID:'.str_pad($id, 6, 0, STR_PAD_LEFT).']';
于 2019-03-01T14:26:39.277 回答
0

您可以使用数据库,但如果您不必在网站中存储其他内容,则一个简单的解决方案是将 ID 存储在文件中:

//Read id
$file = fopen("myfile", "r");
fscanf($file, "%u", $id);
fclose($file);

//Write new id
$file = fopen("myfile", "w");
fprintf($file, "%u", $id + 1);
fclose($file);

如果必须存储更多数据,最简单有效的解决方案是使用数据库,例如带有PDO 类的 MySQL 。

于 2019-03-01T13:54:52.913 回答