我正在尝试从头开始创建一个论坛,但我有点纠结。在下面的代码中,我试图设置一个条件,如果用户未登录,他将无法添加类别。但是,如果用户被记录,代码可以完美运行,但是如果他没有,我会得到一个"未定义的索引:userid"。我试图添加if(isset($_SESSION['userid']))
但这只会隐藏"您必须登录"的通知。有什么好主意吗?
<?php
include("_/inc/dbcon.php");
$link = mysql_connect($host, $login, $pw);
mysql_select_db($database);
if($link){
}
include("_/inc/session_handler.php");
$create_cat ="";
if($_SESSION['userid'] == false /*| $_SESSION['rank'] !='Emperor' || $_SESSION['rank'] !='Destroyer' || $_SESSION['rank']!= 'Tekken Lord' )*/)
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{ echo "YOU HAVE THE RIGHTS!";
//the form hasn't been posted yet, display it
$create_cat .= '<form method="post" action="">
<input type="text" name="cat_name" placeholder="Category Name"/><br />
<input type="text" name="cat_description" placeholder="Category Description" /><br />
<input type="submit" value="Add category" />
</form>';
}
else
{
//the form has been posted, so save it
$sql = "INSERT INTO sp_categories(cat_name, cat_description)
VALUES('" . mysql_real_escape_string($_POST['cat_name']) . "',
'" . mysql_real_escape_string($_POST['cat_description']) . "')";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
else
{
$create_cat .= 'New category succesfully added.';
}
}
}
?>
当您
尝试调用数组的索引时,如果未定义,则会发出未定义的索引错误。
例如:
// Define an array with a few keys and values...
$data = array(
'vehicle' => "car",
'color' => "red",
);
echo $data['size']; // This line will issue an undefined index error...
。因为索引大小不是现有键。
在尝试调用数组之前,请始终检查数组中是否存在密钥:
if (isset($_SESSION['userid']) && $_SESSION['userid'] === false)
PS:我注意到您正在使用mysql_*
函数,这些函数已弃用。请尝试改用PDO
。
当您在数组中查找不存在的键时,会出现未定义的索引错误。尝试使用array_key_exists:http://php.net/manual/en/function.array-key-exists.php
if ( !array_key_exists( 'userid', $_SESSION ) ) {}
希望这有帮助
如果您真的确定您的代码有效(即使这是一个不好的示例(,请使用 error_reporting(E_ERROR);
删除通知。
或者,也许您在错误的地方使用了isset()
。