PHP留言板代码错误修复与优化
The error messages indicate that there are several issues in your code:
-
'Undefined array key "username"': This error occurs because the 'username' key is not present in the
$_POSTarray. Make sure that the input field in your form has the name attribute set to 'username'. -
'Undefined variable $submittedUsername': This error occurs because you have a typo in the variable name. Remove the extra dollar sign in front of 'submittedUsername' in the first line of your code.
-
'Undefined array key "email"' and 'message': Similar to the first error, these errors occur because the corresponding keys are not present in the
$_POSTarray. Make sure that the input fields in your form have the name attributes set to 'email' and 'message'. -
'Undefined variable $username': This error occurs because you have a typo in the variable name. Change '$username' to '$submittedUsername' in the SQL query.
-
'Cannot modify header information': This error occurs because you are trying to use the
header()function after some output has already been sent to the browser. To fix this, move theheader()function to the top of your code, before any output is generated.
Here's the corrected code:
<?php
// 获取表单数据
$submittedUsername = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
// 连接到数据库
$servername = "localhost";
$dbname = "liuyan";
$db_username = "root";
$db_password = "123";
$conn = new mysqli($servername, $db_username, $db_password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 插入数据到数据库
$sql = "INSERT INTO messages (username, email, message) VALUES ('$submittedUsername', '$email', '$message')";
if ($conn->query($sql) === TRUE) {
header("Location: liuyan.html");
exit;
} else {
echo "保存数据时出错: " . $sql . "<br>" . $conn->error;
}
// 关闭数据库连接
$conn->close();
?>
Make sure to double-check your form fields and adjust the code accordingly.
原文地址: https://www.cveoy.top/t/topic/f3BD 著作权归作者所有。请勿转载和采集!