我正面临一些您可以轻松解决的问题。 因为在点击提交按钮时在数据库中存储数据所以在第一次看上去工作的形式。我在刷新配置文件页面后还会存储数据。我认为如果代码只在点击提交按钮上执行,而不是在刷新页面上,它将被解决。但不知道该怎么做。如何仅在点击提交按钮时插入数据?
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
}
}
?>
在此先感谢。
你可以看看插入查询本身。它应该只在数据库中还不存在的情况下插入一个朋友。 –
@usmanikram我不想在有人刷新时将页面重定向到空白页面。 – Nawaraj
@KIKOSoftware当我点击提交按钮时,它工作,但当我刷新配置文件页面时,也插入页面。 – Nawaraj