好的,我正在尝试基本上将两个数据库连接到我的index.php文件,然后使用其中一个数据库来记录用户,并使用其中一个数据库来存储用户的会话。
我无法弄清楚如何存储用户的会话。我想要做的是让用户信息显示,如电子邮件和用户名这样的东西,然后当他们退出时,我希望该信息随会话消失,但目前当用户登录信息时,请保持说明旧用户并没有改变。
我在下面提供了我的代码。在我的代码中,当我提到像它的数据库这样的会话时,因为我创建了一个名为session的数据库和表,而我的另一个数据库被称为数据库,该表称为admin。
索引
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "****";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT id FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$session_id = session_id();
$sql = "INSERT INTO session(session_id,username) VALUES('$session_id','$myusername')";
mysqli_query($db,$sql);
header("Location: test2.php");
}else {
$error = "";
}
}
?>
配置
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '******');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
会话
<?php
include('config.php');
session_start();
$user_check = $_SESSION['myusername'];
$ses_sql = mysqli_query($db,"select username from admin where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
?>
测试2页面(这是我要登录的页面,因此它显示用户信息。)
<?php
session_start();
include("config.php");
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "database";
$dbname2 = "session";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, $dbname2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$session_id = session_id();
$sql = "SELECT id, username, passcode, email, Address, City, Country, Zip, FirstName, LastName, About FROM admin WHERE username = (SELECT username FROM session WHERE session_id = '$session_id')";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
?>
答案 0 :(得分:2)
正如我在评论中所说:
“基本上,您需要做的是将一个会话数组分配给一个post数组,然后将该会话传递给其他页面(并在WHERE子句中查询),然后在注销时销毁该会话。” EM>
所以这是你可以使用的逻辑,并作为一个基本的例子:
旁注:
我很可能需要花更多的时间来检查整个代码来修复它。这更容易/更快。
<?php
session_start();
$_POST['user'] = "John"; // Take the POST array from your named input
if (!isset($_SESSION['var'])) {
$_SESSION['var'] = $_POST['user'];
} else {
echo "It seems the session is already set " . $_SESSION['var'];
}
$username = $_SESSION['var'];
echo $username;
...然后检查会话是否在后续页面中设置并应用相同的逻辑。
还要留意你提问的评论。
销毁会话的参考: