[英]How do I store a $_SESSION value within my database
I've been trying to store the session userUid
and put it in the database under id.我一直在尝试存储会话
userUid
并将其放入数据库中的 id 下。 I want it to merge the two ids from different databases.我希望它合并来自不同数据库的两个 id。
I tried setting the userUid
as a variable and putting it into the database.我尝试将
userUid
设置为变量并将其放入数据库。 userUid
is the id from the signup/login page and profiles is the database i'm trying to insert it into. 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>";
}
}
}
I expect it to out put the newly inserted $_SESSION['userUid']
as "id" from the database profiles.我希望它把新插入的
$_SESSION['userUid']
作为数据库配置文件中的“id”。
A few things to note,有几点需要注意,
exit;
exit;
after a header("Location:...");
header("Location:...");
callnum_rows
(the equivalent is affected_rows
for insert/update/delete queries) or fetch_*()
methods associated with them.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();
In order to properly check for errors, you should enable MySQLi exception mode by adding the following line before you create your MySQLi connection.为了正确检查错误,您应该在创建 MySQLi 连接之前通过添加以下行来启用 MySQLi 异常模式。 That means that you have to use a
try/catch
for your query statements, but in turn means that you don't have to do individual error-checking for each function-call.这意味着您必须对查询语句使用
try/catch
,但反过来意味着您不必对每个函数调用进行单独的错误检查。
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You are trying to use mysqli_fetch_assoc
on an insert query.您正在尝试在插入查询中使用
mysqli_fetch_assoc
。
You could either just use $_SESSION['userUid']
or you can make a seperate select query to get the new row from the database.您可以只使用
$_SESSION['userUid']
或者您可以进行单独的选择查询以从数据库中获取新行。
First check the "if" condition in your code.首先检查代码中的“if”条件。
if(!isset($_SESSION['userUid'])): ... else: ... endif;
The final solution to you,给你的最终解决方案,
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.