2017-10-13 113 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