
本文针对PHP表单提交数据到数据库失败,以及提交后无法正确返回带有ID的URL页面的问题,提供了一个详细的解决方案。通过在表单中添加隐藏字段传递ID值,并在处理脚本中正确获取和使用该ID,确保数据能够成功插入数据库,并实现页面跳转。文章还包含了代码示例和注意事项,帮助开发者避免常见错误,提高开发效率。
在开发Web应用时,经常会遇到需要通过表单向数据库添加数据,并且在操作完成后返回到之前的页面,同时保留URL中的ID参数的情况。如果处理不当,可能会出现数据无法成功写入数据库,或者无法正确返回页面的问题。下面将详细介绍如何解决这个问题。
通常,出现这个问题的原因在于数据在不同的页面之间传递时丢失了关键信息,例如URL中的ID参数。在lid.php页面,URL中包含lidnummer参数,但是在表单提交到create.php页面时,该参数并没有被传递过去。因此,在create.php页面无法通过$_GET['lidnummer']获取到该值,导致数据库操作失败,或者无法正确返回到lid.php页面。
解决这个问题的关键在于确保lidnummer参数在表单提交的过程中被正确传递到create.php页面。一种常用的方法是在表单中添加一个隐藏字段,将lidnummer的值存储在该字段中,然后通过POST方法提交到create.php页面。
立即学习“PHP免费学习笔记(深入)”;
1. 修改表单,添加隐藏字段:
在lid.php页面的表单中,添加一个隐藏的input字段,用于存储lidnummer的值。
<form action="includes/create.php" method="POST">
<input type="hidden" name="lidnummer" value="<?php echo $_GET['lidnummer']; ?>">
<b>
<label for="telefoonnummer">
Telefoonnummer:
<input type="text" name="telefoonnummer">
</label>
<button type="submit" name='add_telnr'>Voeg telnr toe</button>
</b>
</form><br>
<form action="includes/create.php" method="POST">
<input type="hidden" name="lidnummer" value="<?php echo $_GET['lidnummer']; ?>">
<label for="email">
Email:
<input type="text" name="email">
</label>
<button type="submit" name='add_email'>Voeg email toe</button>
</b>
</form><br>
</div>注意: 确保在value属性中正确输出了lidnummer的值。
2. 修改create.php页面,使用POST方法获取lidnummer:
在create.php页面,需要将获取lidnummer的方式从$_GET改为$_POST。
if(isset($_POST['add_telnr'])) {
$telnr = get_post($conn, 'telefoonnummer');
$lidnummer = $_POST['lidnummer']; // 使用$_POST获取lidnummer
$stmt_telnr = $conn->prepare("INSERT INTO telefoonnummers VALUES(?,?)");
$stmt_telnr->bind_param('si', $telnr, $lidnummer);
$stmt_telnr->execute();
if($stmt_telnr->affected_rows != 1) {
echo '<script> alert("Telefoonnummer niet toegevoegd. Waarschijnlijk bestaat deze al. Controleer de lijst en/of probeer het opnieuw.") </script>';
echo '<script> window.location.href = "../lid.php?lidnummer=' . $lidnummer . '" </script>';
} else {
header("location: ../lid.php?lidnummer=" . $lidnummer); // 注意header的正确写法
}
$stmt_telnr->close();
}3. 注意事项:
通过在表单中添加隐藏字段传递ID参数,并在处理脚本中使用$_POST方法获取该参数,可以有效地解决PHP表单提交数据到数据库失败,以及提交后无法正确返回带有ID的URL页面的问题。同时,需要注意安全性、错误处理等方面,确保Web应用的稳定性和安全性。
以上就是解决PHP表单提交数据到数据库失败并返回带ID的URL页面的问题的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号