如何在数据库中存储$ _SESSION值

时间:2019-07-19 04:30:34

标签: php mysql mysqli

我一直在尝试存储会话userUid并将其放在ID下的数据库中。我希望它合并来自不同数据库的两个ID。

我尝试将userUid设置为变量并将其放入数据库中。 userUid是注册/登录页面的ID,个人资料是我试图将其插入的数据库。

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”。

3 个答案:

答案 0 :(得分:2)

一些注意事项,

  • 您当前的逻辑将永远无法真正发挥作用,因为您仅在会话值未设置设置
  • 时执行查询
  • 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);

答案 1 :(得分:0)

您正尝试在插入查询中使用SMTP-Server
您可以只使用mysqli_fetch_assoc,也可以进行单独的选择查询以从数据库中获取新行。

答案 2 :(得分:-1)

首先检查代码中的“ 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;