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