gpt4 book ai didi

php - 刷新页面时表单数据重新发布到数据库

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:07 25 4
gpt4 key购买 nike

我正在尝试学习如何制作将数据发布到数据库的注册表单。在我将教程剥离之前,我无法从教程中获取代码来工作。它现在工作正常,除了如果我刷新页面(删除我输入的值以便我可以输入另一个条目),它会将原始数据重新发布到数据库表。

换句话说,如果我为名字和姓氏输入值 Kelly Kau,然后点击提交按钮,Kelly 和 Kau 就会输入到数据库表中。但是当我刷新页面时,会添加另一行 Kelly 和 Kau。

有办法阻止吗?我正在使用 PHP 和 MySQL。我要复制的教程是 jQuery。最终,我可能还会添加一些 AJAX。

<form id="signupform" autocomplete="off" method="post" action="" novalidate>
<table>
<tr>
<td class="label"><label id="lfirstname" for="firstname">First Name</label></td>
<td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100"></td>
<td class="status"></td>
</tr>
<tr>
<td class="label"><label id="llastname" for="lastname">Last Name</label></td>
<td class="field"><input id="lastname" name="lastname" type="text" value="" maxlength="100"></td>
<td class="status"></td>
</tr>
<tr>
<td class="label"><label id="lsignupsubmit" for="signupsubmit">Signup</label></td>
<td class="field" colspan="2"><input id="signupsubmit" name="signup" type="submit" value="Signup"></td>
</tr>
</table>
</form>
<?php
include('ajax-database/config.php');
$pdo = connect();

try {
$sql = "INSERT INTO g1_members (firstname, lastname) VALUES (:firstname, :lastname)";
$query = $pdo->prepare($sql);
$query->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$query->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);

$query->execute();
} catch (PDOException $e) {
echo 'PDOException : '. $e->getMessage();
}
?>

最佳答案

使用基于您的提交按钮被点击的条件语句:

<?php
include('ajax-database/config.php');
$pdo = connect();

if(isset($_POST['signup'])){

try {
$sql = "INSERT INTO g1_members (firstname, lastname) VALUES (:firstname, :lastname)";
$query = $pdo->prepare($sql);
$query->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$query->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);

$query->execute();

} catch (PDOException $e) {
echo 'PDOException : '. $e->getMessage();
}

} // brace for if(isset($_POST['signup']))

?>

或成功查询时的 header 重定向:

if($query){
header("Location: http://www.example.com");
exit;
}

  • 理想情况下,如果您不想插入相同的值,那么最好将给定的列设置为 UNIQUE。

关于php - 刷新页面时表单数据重新发布到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28017009/

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