我有一个与登录页面一起使用的if语句。
我一直在尝试将其转换为mysqli预备语句。以前只是正常的mysqli。
问题在于,无论我输入什么ID,它都会一直说无效ID!而不是切换到正确的页面。
if (isset($_POST['login']))
{
require "connect.php";
session_start();
if (count($_POST) > 0)
{
if ($stmt = mysqli_prepare($conn, "SELECT id, Login_ID, Name, User_Role_ID FROM user WHERE Login_ID = ?"));
$lid = $_POST["id"];
$stmt->bind_param("i", $lid);
$stmt->execute();
$stmt->bind_result($id, $Login_ID, $Name, $User_Role_ID);
$_SESSION["Student_DB_ID"] = $id;
$_SESSION["Login_ID"] = $Login_ID;
$_SESSION["Name"] = $Name;
$_SESSION["User_Role_ID"] = $User_Role_ID;
switch ($User_Role_ID)
{
case "2":
header("Location: ../views/student/");
break; //Student
case "1":
header("Location: ../views/admin/");
break; //Admin
default:
echo "Invalid ID!";
}
/* close statement */
$stmt->close();
$conn->close();
}
}
答案 0 :(得分:0)
您需要阅读mysqli_stmt_fetch()函数(http://php.net/manual/en/mysqli-stmt.fetch.php)的文档。该函数仅返回布尔值,具体取决于查询是否成功完成。您需要使用bind_result()来返回值。
编辑:
根据下面的评论,此代码应该有效,您还删除了仍然需要的fetch()调用:
if (isset($_POST['login'])) {
require "connect.php";
session_start();
if (count($_POST) > 0) {
if ($stmt = mysqli_prepare($conn, "SELECT id, Login_ID, Name, User_Role_ID FROM user WHERE Login_ID = ?")) {
$lid = $_POST["id"];
$stmt->bind_param("i", $lid);
$stmt->execute();
$stmt->bind_result($id, $Login_ID, $Name, $User_Role_ID);
$stmt->fetch();
$_SESSION["Student_DB_ID"] = $id;
$_SESSION["Login_ID"] = $Login_ID;
$_SESSION["Name"] = $Name;
$_SESSION["User_Role_ID"] = $User_Role_ID;
switch ($User_Role_ID) {
case "2":
header("Location: ../views/student/");
break; //Student
case "1":
header("Location: ../views/admin/");
break; //Admin
default:
echo "Invalid ID!";
}
/* close statement */
$stmt->close();
$conn->close();
}
}
}