2017-10-13 108 views
-2

我正面臨一些您可以輕鬆解決的問題。 因爲在點擊提交按鈕時在數據庫中存儲數據所以在第一次看上去工作的形式。我在刷新配置文件頁面後還會存儲數據。我認爲如果代碼只在點擊提交按鈕上執行,而不是在刷新頁面上,它將被解決。但不知道該怎麼做。如何僅在點擊提交按鈕時插入數據?

Profile.php

<?php 
include('session.php'); 
include('frnd.php'); 
if(!isset($_SESSION['login_user'])){ 
header("location: index.php"); // Redirecting To Home Page 
} 
?> 

<!DOCTYPE html> 
<html> 
<head> 
<title>Your Home Page</title> 
<link href="style.css" rel="stylesheet" type="text/css"> 
</head> 
<body> 
<span><?php echo $error; ?></span> 
<div id="profile"> 
    <b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b> 
    <b id="logout"><a href="logout.php">Log Out</a></b> 
</div><br> 
<form action="" method="post"> 
<input type="text" name="frndIn" required><input type="submit" name="add"> 
</form> 
</body> 
</html> 

Frnd.php

<?php 
    $error = ''; // Variable To Store Error Message 
    if (isset($_POST['add'])) { 
    if (empty($_POST['frndIn'])) { 
    $error = "Please enter username of your friend"; 
    } 
    else 
    { 
    $frndIn = $_POST['frndIn']; 
    // mysqli_connect() function opens a new connection to the MySQL server. 
    $conn = mysqli_connect("localhost", "root", "", "msg"); 
    $query = "INSERT INTO friend (username, friend) values (?,?)"; 
    // To protect MySQL injection for Security purpose 
    $stmt = $conn->prepare($query); 
    $stmt->bind_param("ss", $login_session, $frndIn); 
    if ($stmt->execute()) 
     { 
      echo "New record inserted successfully"; 
     } 
    else 
     { 
      $error = 'Error occur'; 
     } 
    mysqli_close($conn); // Closing Connection 
    } 
    } 
    ?> 

在此先感謝。

+0

你可以看看插入查詢本身。它應該只在數據庫中還不存在的情況下插入一個朋友。 –

+0

@usmanikram我不想在有人刷新時將頁面重定向到空白頁面。 – Nawaraj

+0

@KIKOSoftware當我點擊提交按鈕時,它工作,但當我刷新配置文件頁面時,也插入頁面。 – Nawaraj

回答

0

驗證併成功插入Frnd.php數據庫後,您需要將用戶/客戶端重定向回您的Profile.php。

+0

如果你看一下profile.php代碼,你會發現include('frnd.php');這樣用戶點擊提交按鈕後,frnd.php也會在同一頁面執行。從Profile.php – Nawaraj

+0

重定向到Profile.php並不是好主意點擊提交後,您的頁面將使用POST方法提交表單。這就是爲什麼當您重新加載頁面(「我應該再次發佈數據?」)時,您會從瀏覽器中獲得確認對話框。重定向到Frnd.php的Profile.php將使用GET方法重定向。包含的Frnd.php將被包含在內,但沒有代碼正在執行,因爲它只在$ _POST ['add']被設置時觸發。 – kerbholz