GeorGios GeorGios - 4 months ago 6
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:

<ul>
<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>
<?php
if (isset($_SESSION['id'])){
echo "<li><a href='#'>SIGN OUT</a></li>";
}
else{
echo "<li><a onclick='signup(event)' href='#'>SIGN UP</a></li>";
}
?>
</ul>


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

<?php
session_start();
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");
exit();


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

This:

$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);
NULL

You want

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

instead.