我试图弄清楚为什么我可以连接到数据库,但无法访问其中的数据。
这是我的配置:
//config.php
<?php
define("HOST", "MYSERVERNAMEISHERE");
define("DATABASE", "users");
?>
我的用户登录,并传递他们的信息进行检查:
//login.php
<?php
if ($_POST) {
if ($_POST["user"] && $_POST["password"]) {
include_once "config.php";
define("USER", $_POST["user"]);
define("PASSWORD", $_POST["password"]);
$link = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($link) {
$link->close();
if ($_SESSION) {
session_destroy();
}
session_start();
$_SESSION["user"] = $_POST["user"];
$_SESSION["password"] = $_POST["password"];
}
}
}
if ($_SESSION) {
header('Location: profile.php');
}
else {
header('Location: login.html');
}
?>
当他们通过时,他们可以看到他们的个人资料页面。
//profile.php
<?php
session_start();
if (!$_SESSION["user"] || !$_SESSION["password"]) {
session_destroy();
header("Location: login.html");
}
else {
include_once "config.php";
}
$link = new mysqli(HOST, USER, PASSWORD, DATABASE) or die("Unable to connect to database");
$result = $link->query("SHOW TABLES") or die("Unable to show tables");
...
ADDITIONAL PHP AND HTML CODE AFTER THIS POINT
问题是当我尝试查询 mysqli 链接时,进程会死亡。(我得到Unable to show tables
)现在,SHOW TABLES
只是调试的填充物;当我找出问题时,我实际上会有有用的 mysqli 查询。
请帮助我确定我的错误在哪里。如果您为我找到错别字或参考链接,很抱歉浪费您的时间。我已经研究和调试了几个小时了。
提前非常感谢。
PS:如果您对我应该做出的更改有一些好的建议,我也非常感谢。这是我第一次让用户登录。
配置文件
中的查询.php失败,因为未定义USER
和PASSWORD
。当此人登录时,他们在登录.php中定义。当重定向到配置文件.php时,USER
AND PASSWORD
没有值,因为它们不在 config.php 中。
在配置文件.php中,更改
$link = new mysqli(HOST, USER, PASSWORD, DATABASE) or die("Unable to connect to database");
自
$link = new mysqli(HOST, $_SESSION["user"], $_SESSION["password"], DATABASE) or die("Unable to connect to database");