GeorGios GeorGios - 1 year ago 35
PHP Question

PHP: $_SESSION doesn't set

Before setting as duplicate, I've spent 4 hours on researching about my problem, but I had no luck.

I am trying to make a signup/login system for my website. The main point that doesn't seem to work is that when I am signing up on my website, the session doesn't seem to start. The reason that I can see it is because, on my navbar, I have set it to change from signup to log out. Here is the piece of code for that:

<li class="list1"><a href="GeorgeKarabassis.php">Home</a></li>
<li class="list2"><a href="about.php">About</a></li>
<li class="list3"><a href="portfolio.php">Portfolio</a></li>
<li class="list4"><a href="Blog.php">Blog</a></li>
<li class="list4"><a href="contact_us.php">Contact</a></li>
if (isset($_SESSION['id'])){
echo "<li><a href='#'>SIGN OUT</a></li>";
echo "<li><a onclick='signup(event)' href='#'>SIGN UP</a></li>";

To make that I have created three files. One is the mane page, one is the signup file itself, code below:

include "../dbh.php";

$first = $_POST["first"];
$last = $_POST["last"];
$uid = $_POST["uid"];
$email = $_POST["email"];
$pwd = $_POST["pwd"];

$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];
header("Location: ../index.php");

and the last one is the file which connects PHP to the database code below:

$conn = mysqli_connect("XXX","XXX","XXX","XXX");

if (!$conn){
die("Connection failed: ".mysqli_connect_error());

I believe that the session doesn't start because the main page reloads after the user hits signup on the form, but I have started the session on all of my files (except the database connection file where it's not needed). I used session start on all of my page and I placed it on the beginning of all pages with opening and closing PHP tags.

Any suggestions? I appreciate your answers and comments!

Sorry for the bad English but it's not my first language.

Answer Source


$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];

Insert queries do NOT return a result set, and you can NOT fetch() from them. That means mysqli_fetch_assoc() is failing, and returning a boolean FALSE. You then use that boolean false as if it was an array, and are basically doing the equivalent of

$_SESSION['id'] = null;

Note this:

php > $foo = false;
php > $id = $foo['id'];
php > var_dump($id);

You want

$_SESSION['id'] = mysqli_insert_id($conn);