gpt4 book ai didi

php - 在 PHP 中重新加载浏览器时自动插入以前的数据

转载 作者:行者123 更新时间:2023-11-29 04:38:32 25 4
gpt4 key购买 nike

我有一些数据输入区域。这是我的文件。

这是我的 db.php:

<?php

$username = "root";
$password = "";

try {
$db = new PDO('mysql:host=localhost;dbname=task', $username, $password);
echo "Connection Successfull";
} catch (PDOException $e) {
die("Error: Database connection");
}

?>

我的 index.php 是:

<?php 
include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" value="Submit">
</form>
</div>

<?php
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;

?>
</body>
</html>

当我第一次访问 index.php 页面时,它会显示一些通知。

Notice: Undefined index: name in C:\xampp\htdocs\techmasters\begin\index.php on line 21

Notice: Undefined index: email in C:\xampp\htdocs\techmasters\begin\index.php on line 22

Notice: Undefined index: website in C:\xampp\htdocs\techmasters\begin\index.php on line 23

但是,如果我输入任何数据,那么它会被正常插入。我的问题是,如果我重新加载浏览器,那么之前插入的数据将再次插入。我该如何解决这个问题?

提前致谢。

最佳答案

这是因为,您没有检查表单是否已提交。

在每个页面请求中,数据被插入,添加一个检查。

<?php
if (isset($_POST['name']) && ! empty($_POST['name'])) {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if (empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
$_POST = NULL;
}
?>

这将确保仅在表单提交时才进行数据库插入。

编辑:

If you submit a form to same page and then reload the page, it will ask you to resubmit the form. Either change method to get and check for duplicity or submit the form to another file (move form submit code to other file and set it as form action).

关于php - 在 PHP 中重新加载浏览器时自动插入以前的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com