這是我的主頁的代碼:與在同一頁上從表單中的值更新表
<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關閉。有任何想法嗎?
你正在使用'header(「Location:testphp.php」);'提前。當然,如果請求是「POST」,它已經完成了它的工作。你需要在「成功查詢你的數據庫」之後放置'header(「Location:testphp.php」);'「。 –
我已經嘗試在獲取值後放置標題,但我收到了此類型的警告。警告:無法修改標題信息 - 已在第23行的/some/file.php中(通過/some/file.php:12開始輸出)發送的標頭 – captain
您是否正在使用會話? –