user2001394
user2001394

Reputation: 11

UNDEFINED INDEX role?

<?php
if(isset($_SESSION['username'],$_SESSION['password']))
 $role = $_SESSION['role'];
 if($_SESSION["role"] == "member"){
?>

<form name ="add_cart" method="post" action="Shoppingcart.php" onSubmit="alert('Item added!')">
 <input type='hidden' name='id' id="id" value='<?php echo $id; ?>'>
<input  type="text" name="quantity" id="quantity" value="1" size="3" maxlength="3">
<input  type="submit" name="Add" value="ADD TO CART" style="width:150px; background-color:black; border:none; color:White "/>
                </td>
            </form>

        <?php
    }}

    ?>

And here's my error:

NOTICE: UNDEFINED INDEX: ROLE IN C:\XAMPP\HTDOCS\FYP2\FOODCATALOG.PHP ON LINE 181

Upvotes: 0

Views: 1957

Answers (3)

anon
anon

Reputation:

You should assing a value to $_SESSION['role']; before all else. Fast but simple way is..

<?php
if(isset($_SESSION['username'],$_SESSION['password']))
  $_SESSION['role'] = 1;
  $role = $_SESSION['role'];
 if($_SESSION["role"] == "member"){
?>

Upvotes: 0

shafiq.rst
shafiq.rst

Reputation: 1296

if(isset($_SESSION["role"]) && $_SESSION["role"] == "member"){

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

That means $_SESSION['role'] is not set. This is likely happening at this line:

$role = $_SESSION['role'];

You should ALWAYS check for the existence of an array key before using it unless you absolutely know that it will be set (i.e. you hard code it elsewhere in your code). So something like this

$role = '';
if(!empty($_SESSION['role'])) {
    $role = $_SESSION['role'];
}

You should then also update you conditional to use $role and not $_SESSION['role'].

if($role == "member") {

Here you know that $role is guaranteed to be set, so it is safe to use this in a conditional.

Upvotes: 2

Related Questions