[英]How do I store a $_SESSION value within my database
我一直在嘗試存儲會話userUid
並將其放入數據庫中的 id 下。 我希望它合並來自不同數據庫的兩個 id。
我嘗試將userUid
設置為變量並將其放入數據庫。 userUid
是注冊/登錄頁面中的 id,profiles 是我試圖將其插入的數據庫。
if(!isset($_SESSION['userUid'])){
header("location: index.php"); // Redirecting To Home Page
$switch = $_SESSION['userUid'];
$Asql = "INSERT INTO profile (id) VALUES ('$switch');" ;
mysqli_query($conn2, $Asql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'] . "<br>";
}
}
}
我希望它把新插入的$_SESSION['userUid']
作為數據庫配置文件中的“id”。
有幾點需要注意,
exit;
在header("Location:...");
稱呼num_rows
(相當於是affected_rows
的插入/更新/刪除查詢)或fetch_*()
與它們相關的方法。if (!isset($_SESSION['userUid'])) {
header("location: index.php"); // Redirecting To Home Page
exit;
}
$sql = "INSERT INTO profile (id) VALUES (?);";
$stmt = $conn2->prepare($sql);
$stmt->bind_param("s", $_SESSION['userUid']);
$stmt->execute();
echo $stmt->affected_rows." rows inserted";
$stmt->close();
為了正確檢查錯誤,您應該在創建 MySQLi 連接之前通過添加以下行來啟用 MySQLi 異常模式。 這意味着您必須對查詢語句使用try/catch
,但反過來意味着您不必對每個函數調用進行單獨的錯誤檢查。
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
您正在嘗試在插入查詢中使用mysqli_fetch_assoc
。
您可以只使用$_SESSION['userUid']
或者您可以進行單獨的選擇查詢以從數據庫中獲取新行。
首先檢查代碼中的“if”條件。 if(!isset($_SESSION['userUid'])): ... else: ... endif;
給你的最終解決方案,
if(!isset($_SESSION['userUid'])):
header("location: index.php"); // Redirecting To Home Page
else:
$switch = $_SESSION['userUid'];
$Asql = "INSERT INTO profile (id) VALUES ('$switch');" ;
mysqli_query($conn2, $Asql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0):
while ($row = mysqli_fetch_assoc($result))
{
echo $row['id'] . "<br>";
}
endif;
endif;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.