[英]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.