[英]Insert same data into database
我有一個基於網絡的表格,可以接收學生信息。 插入數據后,即使刷新瀏覽器,我仍希望它仍然可用。這意味着2行相同,但我不想再次插入相同的數據。 這怎么可能?
我的代碼在這里:
<form method="post" action="insert.php" >
<table>
<tr>
<td width="22%"> Name</td>
<td width="4%"></td>
<td width="74%"><input type="text" name="name" > </td>
</tr>
<tr>
<td>Information </td>
<td></td>
<td><input type="text" name="infomn" ></td>
</tr>
<tr>
<td>Email </td>
<td></td>
<td><input type="text" name="email" ></td>
</tr>
<tr>
<td>Password </td>
<td></td>
<td><input type="password" name="password" ></td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td></td>
<td></td>
<td ><input type="submit" name="submit" value="Insert" >
</td>
</tr>
</table>
</form>
insert.php:
include("connect.php");
if($_POST['submit']){
$name=$_POST[name];
$info=$_POST[infomn];
$emal=$_POST[email];
$password=$_POST[password];
$query = "insert into student(name,designation,email,password) values('$name','$info','$emal','$password')";
mysql_query($query) or die("not successfully insert".mysql_error());
?>}
在嘗試插入數據之前,我將檢查您的值是否已填充。
if ($_POST['name']) {
//Validate, escape, insert...
} else {
//Display form...
}
請確保您插入數據庫中的數據已轉義 ,尤其是在處理學生數據時。
現在看起來像這樣:
為了避免這種情況,您必須添加
header("Location: index.php");
或一些類似的代碼,以確保執行數據庫執行后用戶不會停留在同一頁面上。
瀏覽器刷新將上一次操作(再次)發布到服務器。
使用發布/重定向/獲取模式 ( http://en.wikipedia.org/wiki/Post/Redirect/Get ),即始終在成功執行操作后進行重定向(在您的情況下為數據庫插入)。
insert.php:
include("connect.php");
if(isset($_POST['submit'])) { // put isset() for checking if it submitted or not
$name=$_POST['name'];
$info=$_POST['infomn'];
$emal=$_POST['email'];
$password=$_POST['password'];
$query = "insert into student(name,designation,email,password)
values('$name','$info','$emal','$password')";
if(mysql_query($query)) {
header('Location:your_form_page.php'); // redirect to avoid inserting data while refreshing
}else {
mysql_error() };
}
建議:嘗試使用PDO 如何防止在PHP中進行SQL注入?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.