Lewis Hoggerson
Lewis Hoggerson

Reputation: 37

PHP Array to string conversion $_SESSION

Hey guys so I've come across what seems to be a strange issue when trying to output some SQLi data when retrieving it and assigning it to a $_SESSION. I'm quite new to PHP so the chances are I'll be doing something stupid..

So here is my login.php PHP section:

<?php
require 'connections.php';
if(isset($_POST['Login'])){

    $EM = $_POST['Email'];
    $PW = $_POST['Password'];

    $result = $con->query("SELECT * FROM users where Email='$EM'");

    $row = $result->fetch_array(MYSQLI_BOTH);

    if(password_verify($PW, $row['Password'])){


    session_start();

    $_SESSION["UserID"] = $row['UserID'];
    $_SESSION["FirstName"] = $row=['Firstname'];

    header('Location: account.php');
    }
    else{
        session_start();
        $_SESSION['LogInFail'] = "Yes";
    }

}
?>

So above I believe I set my $_SESSION["FirstName"] to the users Firstname which is being selected from the database.

Then here is part of my account.php PHP code:

<?php
 require 'connections.php';
 session_start();
 if(isset($_SESSION['UserID'])){
 }
 else {
    header('Location: login.php');
 }
 ?>

Then here is the problem:

<b>Welcome to your account <?php echo $_SESSION['FirstName']; ?>!</b>

It is returning this error:

Welcome to your account
Notice: Array to string conversion in C:\Users*\Desktop\XAMMP\htdocs\PHP\Website\account.php on line 36
Array!

Thanks for reading and if you need any more information let me know!

Upvotes: 1

Views: 2660

Answers (2)

Darwin von Corax
Darwin von Corax

Reputation: 5246

This is a "gotcha" that nailed me a few times at first. To make variable expansion work with an array value with a quoted key, you need to use "complex syntax" i.e.

<b>Welcome to your account <?php echo {$_SESSION['FirstName']}; ?>!</b>

enclosing the variable reference in braces.

Upvotes: 0

Jack Hales
Jack Hales

Reputation: 1644

Go ahead and change the

$_SESSION['FirstName'] = $row=['FirstName'];

To

$_SESSION['FirstName'] = $row['FirstName'];

And that should fix it :)

Upvotes: 1

Related Questions