简体   繁体   English

如何在 php 表单重定向后增加一个数字?

[英]How do I increment a number after a php form redirect?

I'm building a simple count display for a website and I need it to only increment after the form successfully submits.我正在为网站构建一个简单的计数显示,我只需要在表单成功提交后才增加它。 The form is a simple HTML form that uses PHP mail() function to send the information and redirects back to the page.该表单是一个简单的 HTML 表单,它使用 PHP mail() 函数发送信息并重定向回页面。

    let clicks = Number(document.getElementById("clicks").innerHTML);
    function stateInc() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    }

I thought maybe I would use the onClick="function()" tag inside the button to call a function to increment the number on page which is stored in a tag with the appropriate id reference.我想也许我会使用按钮内的 onClick="function()" 标签来调用一个函数来增加页面上的数字,该数字存储在具有适当 id 引用的标签中。

    <p class="for-text">State Hats Ordered:  <a id="clicks">0</a></p>

    <p><button class="for-text" id="clicker" formaction="mailform.php" onclick="stateInc()" style="color: darkred; padding: 8px 8px; margin: 4px;">Submit Order</button></p>

I was hoping to do the increment before leaving the page or even in the php form, but I'm not sure how I would do that and so far what I've attempted hasn't worked thus far.我希望在离开页面之前或什至在 php 表单中进行增量,但我不确定我将如何做到这一点,到目前为止我所尝试的还没有奏效。

I also thought I would try doing a redirect within the javascript function above to go to the form mailer script, but for obvious reasons that wouldn't work due to not having the form information by the time the redirect happens.我还想我会尝试在上面的 javascript 函数中进行重定向以转到表单邮件程序脚本,但由于在重定向发生时没有表单信息,这显然不起作用。

Thanks in advance!提前致谢!

There two ways: 有两种方法:

1. Storing on client side 1.在客户端存储

Advantage: It's cheap and easy 优点:便宜又容易

Disadvantage: counts are user specific and not global/total. 缺点:计数是特定于用户的,而不是全局/总数。 Therefore noone can tell how often a page has been submitted. 因此,没有人能说出提交页面的频率。

let clicks = localStorage.getItem("clicks") || 0; // get value
clicks++;
document.querySelector("#clicks").innerText = "You've visited this page " + clicks + " time(s)"; // display on webpage
localStorage.setItem("clicks", clicks); // save value to client

2. Storing on server side (Highly recommended) 2.在服务器端存储(强烈建议)

Advantage: Total count 优势:总数

Disadvantage: Takes a lil' bit more effort 缺点:需要一点点的努力

Since you are using php I assume you'd rather use mysql. 由于您使用的是PHP,因此我假设您宁愿使用mysql。 You have to create a database and a new table in it. 您必须在其中创建一个数据库和一个新表。 From this point you could track the visit or just the counter. 从这一点上,您可以跟踪访问,也可以仅跟踪柜台。 For instance, you could create the following table: visits(id, ip, time, url) Then you establish a mysql connection and run this sql command INSERT INTO visits (ip, time, url) VALUES(?,?,?) Keep in mind that you don't want any security issues especially when it comes to sql injections. 例如,您可以创建下表: visits(id, ip, time, url)然后建立mysql连接并运行此sql命令INSERT INTO visits (ip, time, url) VALUES(?,?,?)保持请记住,您不需要任何安全性问题,尤其是在涉及到sql注入时。 if you've never heard of it, you should definitely read about it. 如果您从未听说过它,则一定要阅读它。

To display the amount of visits run this sql command after the previous one: SELECT COUNT(id) FROM visits 要显示访问量,请在上一个命令之后运行此sql命令: SELECT COUNT(id) FROM visits

To store the visit: 要存储访问:

$db = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

$query = $db->prepare("INSERT INTO visits (ip, time, url) VALUES(?,?,?)");
$query->bind_param("sss", $_SERVER["REMOTE_HOST"], date("Y-m-d H:i:s"), $_SERVER["REQUEST_URI"]);
$query->execute();
$query->close();
$db->close();

To display the visit counter: 要显示访问计数器:

$db = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

$query = $db->prepare("SELECT COUNT(id) FROM visits WHERE url = ?");
$query->bind_param("s", $_SERVER["REQUEST_URI"]);
$query->bind_result($clicks);
$query->execute();
$query->fetch();
echo "This page was" . $clicks . " time(s) visited";
$query->close();
$db->close();

Notice: Make sure you implement error checking before running this in production 注意:在生产环境中运行此程序之前,请确保执行错误检查

In the end it might be easier to just leave it out or save the page count to a file if you not sure how to use mysql. 最后,如果不确定如何使用mysql,则将其忽略或将页数保存到文件中可能会更容易。

try to use PHP Session. 尝试使用PHP Session。

A session is started with the session_start() function. 使用session_start()函数启动会话。

Session variables are set with the PHP global variable: $_SESSION. 会话变量使用PHP全局变量$ _SESSION设置。

If you just need to increment your counter without anything else after that, you can store the value of the current counter in a .txt file on your server and use it each time to check the current value and then, increment 1 after your form is sended. 如果之后只需要增加计数器,则可以将当前计数器的值存储在服务器上的.txt文件中,并在每次检查当前值时都使用它,然后在表格为已发送。

BUT as Kevin says, the best way is to store it with php in a small database. 但正如Kevin所说,最好的方法是将它与php一起存储在一个小型数据库中。

If your not going to use a database then the best way to do this in a file is to simply append a new line. 如果您不打算使用数据库,那么在文件中执行此操作的最佳方法是简单地添加新行。

When trying to update a value stored in the file, you have to read that value, change it in PHP, then save it. 尝试更新文件中存储的值时,您必须读取该值,在PHP中进行更改,然后保存。 If it's not done with an exclusive lock on the file you could have concurrency and race issues. 如果不对文件进行排他锁,则可能会出现并发和竞速问题。 Basically 2 processes can read it, one increments it, then the other increments the old value so you miss a increment or worse. 基本上有2个进程可以读取它,一个进程将其递增,然后另一个进程将旧值递增,因此您错过了递增值或更差的值。

So you can just append a new row and then there is no read involved in updating the count. 因此,您可以仅追加一个新行,然后更新计数就不会涉及任何读取。

 file_put_contents($filename, "1\n",  FILE_APPEND);

So then how do we count the lines in the file, the number of lines equal the number of increments. 因此,我们如何计算文件中的行数,即行数等于增量数。

$Obj = new SplFileObject($filename, 'r');
$Obj->seek(PHP_INT_MAX); //seek to the max PHP int, or the end of the file
$line = $Obj->key();

You should manage the counter in PHP and show the updated value in the form page. 您应该在PHP中管理计数器,并在表单页面中显示更新的值。 You could store the value in a database. 您可以将值存储在数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM