
本文旨在帮助开发者解决在使用PHP表单提交数据到数据库时,数据插入失败以及无法正确返回带有ID的原始页面的问题。通过分析常见错误原因,提供详细的解决方案和示例代码,确保数据能够成功提交,并顺利返回到指定页面。本文将重点讲解如何正确传递ID参数,以及如何处理数据库操作中的潜在问题。
问题的核心在于lidnummer(ID)参数在lid.php、表单和create.php之间没有正确传递。当表单提交到create.php时,$_GET['lidnummer']是不可用的,因为表单并没有传递这个参数。
解决方案:使用隐藏的input字段传递ID
在表单中添加一个隐藏的input字段,将lidnummer的值传递到create.php。
立即学习“PHP免费学习笔记(深入)”;
<form action="includes/create.php" method="POST">
<b>
<label for="telefoonnummer">
Telefoonnummer:
<input type="text" name="telefoonnummer">
</label>
<input type="hidden" name="lidnummer" value="<?php echo $_GET['lidnummer']; ?>">
<button type="submit" name='add_telnr'>Voeg telnr toe</button>
</b>
</form><br>
<form action="includes/create.php" method="POST">
<label for="email">
Email:
<input type="text" name="email">
</label>
<input type="hidden" name="lidnummer" value="<?php echo $_GET['lidnummer']; ?>">
<button type="submit" name='add_email'>Voeg email toe</button>
</b>
</form><br>
</div>在create.php中,使用$_POST['lidnummer']来获取ID值:
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); // 确保URL正确构造
exit(); // 添加exit()以确保header()之后脚本停止执行
}
$stmt_telnr->close();
}注意事项:
以下是一些关于数据库操作的建议,以提高代码质量和安全性:
<?php
// 包含数据库连接文件
include 'db_connect.php';
// 函数用于安全地获取POST数据
function get_post($conn, $var) {
return htmlspecialchars($conn->real_escape_string($_POST[$var]));
}
if(isset($_POST['add_telnr'])) {
$telnr = get_post($conn, 'telefoonnummer');
$lidnummer = $_POST['lidnummer'];
// 使用预处理语句
$stmt_telnr = $conn->prepare("INSERT INTO telefoonnummers (telefoonnummer, lid_table) VALUES (?, ?)");
$stmt_telnr->bind_param('si', $telnr, $lidnummer);
if ($stmt_telnr->execute()) {
// 插入成功
header("location: ../lid.php?lidnummer=" . $lidnummer);
exit();
} else {
// 插入失败
echo '<script> alert("Telefoonnummer niet toegevoegd: ' . $conn->error . '") </script>';
echo '<script> window.location.href = "../lid.php?lidnummer=' . htmlspecialchars($lidnummer) . '" </script>';
}
$stmt_telnr->close();
}
// 关闭数据库连接
$conn->close();
?>总结
解决PHP表单提交数据到数据库失败并返回原ID页面的问题的关键在于:
通过以上步骤,可以有效地解决数据提交和页面跳转的问题,并提高代码的安全性。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号