这是我的主页代码:
<html>
<head>
<title>PHP test</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="formDiv">
<form action="testsql.php" method="post">
Email: <input type="text" name="email"><br>
<textarea name="comment" rows="10" cols="40">Your comment here.</textarea>
<input type="submit" value="submit">
</form>
<div id="show">
<?php
$con=mysqli_connect("","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Comments");
echo "<table border='1'>
<tr>
<th>Email</th>
<th>Comment</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td>" . $row['comment'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
</div>
</body>
</html>
这是testsql.php文件的代码:
<?php
$con=mysqli_connect("","root","","my_db");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
header("Location: testphp.php");
if(empty($_POST["comment"]))
{echo "You have to write something. <br>";}
else
{
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(empty($_POST["email"]))
{
$sql="INSERT INTO Comments (Email, comment)
VALUES
('$_POST[email]', '$_POST[comment]')";
echo "1 record added.";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
else{
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$_POST["email"]))
{
echo "Invalid email format <br>";
}
else{
echo "Your email is: {$_POST["email"]} <br>";
$sql="INSERT INTO Comments (Email, comment)
VALUES
('$_POST[email]', '$_POST[comment]')";
echo "1 record added.";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
}
}
?>
我想要做的是从表单中获取值并将它们放在表中。单击“提交”按钮后,应该更新该表。当我有header(Location: "testphp.php");
时,它会工作,但如果用户以错误的方式写邮件或不写评论,它就不会显示错误消息。
当我不包含标题时,代码正常工作,但我被重定向到 testsql.php ,我必须返回 testphp.php 才能看到更新表。我知道我可以使用javascript,但我们的教授告诉我们网站应该完全可用,关闭javascript 。有什么想法吗?