【发布时间】:2017-10-13 07:39:32
【问题描述】:
我遇到了一些问题,您可以轻松解决。 我在第一次看时做得很好的表单,因为它在单击提交按钮时将数据存储在数据库中。在我刷新 个人资料页面 后,它还会存储数据。我认为如果代码仅在单击提交按钮时执行而不是在刷新页面时执行,这将得到解决。但不知道该怎么做。
配置文件.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
}
}
?>
编辑:我通过使用 POST/Redirect/GET 方法解决了这个问题。这个视频 (https://www.youtube.com/watch?v=bIkqNHyj25w) 很有帮助。
【问题讨论】:
-
您可以查看的是插入查询本身。它应该只在数据库中尚不存在好友时插入好友。
-
@usmanikram 我不想在有人刷新时将页面重定向到空白页面。
-
@KIKOSoftware 当我点击提交按钮时它可以工作,但当我刷新个人资料页面时它也会插入页面。
-
@Nawaraj 如果我能很好地理解您的问题,那么每当您刷新页面时,您的浏览器都会询问您是否要再次发布数据。要解决此问题,您必须在插入后将页面重定向到另一个页面。在您的情况下,您可以再次将其重定向到 Profile.php
-
实际引用只使用块状引用,并谨慎使用粗体来强调,不要引起注意,所以请删除它。