簡體   English   中英

將相同的數據插入數據庫

[英]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...
}

確保您插入數據庫中的數據已轉義 ,尤其是在處理學生數據時。

現在看起來像這樣:

  1. 信息發布到insert.php
  2. 您位於insert.php中,並且發布的變量也存在。
  3. 數據庫執行是使用現有數據執行的。
  4. 您刷新。
  5. 您永遠不會真正離開該頁面,因為刷新使您可以轉到同一頁面,因此瀏覽器假定發布的數據不應刪除,而應再次使用。

為了避免這種情況,您必須添加

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM