I’ve got a login system set up, and there are no problems with staying logged in. Both userid and username are stored as session variables (and stored in a table in the database), and I can access them for use within the html on the pages themselves just fine.
I have a form with several multiple choice questions. Any answers I put in the form are stored in the database correctly, no problems there. But when I try to put the username or id into the table, it doesn’t work.
The username is displayed on survey.php (the page with the form on it) in the html, like so:
<h2><?php echo $_SESSION['userName']; ?></h2>
Before I submit the form, the username is displayed correctly. After submitting the form, the same page reloads and the username is still displayed correctly. I’m not being logged out. $_SESSION[‘userName’] is not being reset and it’s not empty.
The code below works perfectly as is, but if I replace
$locationMC = $_POST['locationMC'];
with
$locationMC = $_SESSION['userName']; # (the commented out line in the code below)
it redirects me to /survey.php?error=emptyfields, so $locationMC isn’t being set when I try to use the session variable.
The users table and testingtable are in the same database. UserID is set as the primary key, but userName isn’t indexed.
Something tells me I’m missing something super basic here — I’m really new to this — but after hours of searching on google, I can’t figure out what the problem is. Thanks for any help!
<?php if (isset($_POST['submit'])) { require 'dbh.inc.php'; $locationMC = $_POST['locationMC']; # $locationMC = $_SESSION['userName']; $genderMC = $_POST['genderMC']; $religionMC = $_POST['religionMC']; if (empty($locationMC)) { header("Location: ../survey.php?error=emptyfields"); exit(); } else { $sql = "INSERT INTO testingtable (locationMC, genderMC, religionMC) VALUES (?, ?, ?)"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { header("Location: ../survey.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $locationMC, $genderMC, $religionMC); mysqli_stmt_execute($stmt); header("Location: ../survey.php"); exit(); } } mysqli_stmt_close($stmt); mysqli_close($conn); } else { header("Location: ../survey.php"); exit(); }
Below is dbh.inc.php. It’s the same file that’s used when signing up and logging in.
<?php $servername = "localhost"; $dBUsername = "root"; $dBPassword = ""; $dBName = "testingdb"; $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName); if (!$conn) { die("Connection failed: ".mysqli_connect_error()); }
Advertisement
Answer
you need to start request session to read its content
add this code in you top header
if(!isset($_SESSION)) session_start();