Unable to get session variable to save into my database - php

Can anyone help me in getting the group_id from a session and save into the database, it seems not to working, been working on it for a while now. The error i am getting is Notice: Undefined index: group_name
This is my script
include('db.php')
//Get User Info
if(isset($_SESSION['username'])){
$LoggedUser = $_SESSION['username'];
if($GetUser = $mysqli->query("SELECT * FROM users WHERE username='$LoggedUser'")){
$UserInfo = mysqli_fetch_array($GetUser);
$LoggedUsername = strtolower($UserInfo['username']);
$LoggedUserLink = preg_replace("![^a-z0-9]+!i", "-", $LoggedUsername);
$LoggedUserLink = strtolower($LoggedUserLink);
$UserId = $UserInfo['user_id'];
$GetUser->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
}
//Get Group info
if(isset($_SESSION['group_name'])){
$LoggedGroup = $_SESSION['group_name'];
if($GetGroup = $mysqli->query("SELECT * FROM groups WHERE group_name='$LoggedGroup'")){
$GroupInfo = mysqli_fetch_array($GetGroup);
$LoggedGroupname = strtolower($GroupInfo['group_name']);
$LoggedGroupLink = preg_replace("![^a-z0-9]+!i", "-", $LoggedGroupname);
$LoggedGroupLink = strtolower($LoggedGroupLink);
$GroupId = $GroupInfo['group_id'];
$GetGroup->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
}
//getting variables and inserting into a database
if($_POST)
{
$User = $UserId;
$Group = $GroupId;
$mysqli->query("INSERT INTO tb_name(group_id_fk, user_id_fk) VALUES ('$Group', '$User')");
die('<div class="alert alert-success" role="alert">You have been added successfully to the group.</div>');
}else{
die (mysqli_error());
}
?>
Thanks

A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
<?php
// Start the session
session_start();
// Set session variables
if(isset($_SESSION['username'])) {
---- Your Statements -----
}
?>

you need to start a session first by session_start(); before using $_SESSION global

Related

Notice: Undefined index: SESS_NAME in student_vote.php on line 9

<?php
include "connection.php";
if(!isset($_SESSION))
{
session_start();
}
$cand1 = $_POST['cand1'];
$cand2 = $_POST['vice1'];
$sess = $_SESSION['SESS_NAME'];
if(!$cand1){
$error="<center><h4><font color='#FF0000'>Please fill empty fields</h4></center></font>";
include"student.php";
exit();
}
$cand1 = addslashes($cand1);
$cand1 = mysqli_real_escape_string($con,$cand1);
$sql = 'SELECT * FROM student WHERE username="'.$_SESSION['SESS_NAME'].'" AND status="VOTED"';
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result)==1){
$msg="<center><h4><font color='#FF0000'>You have already been voted, No need to vote again</h4></center></font>";
include 'student.php';
exit();
}
else{
$sql = 'UPDATE candidate SET votecount = votecount + 1 WHERE cand_id = "'.$_POST['cand1'].'" OR cand_id = "'.$_POST['vice1'].'"';
$sql2 = 'UPDATE student SET status="VOTED" WHERE username="'.$_SESSION['SESS_NAME'].'"';
$result = mysqli_query($con,$sql);
$result2 = mysqli_query($con,$sql2);
if(!$result && !$result2){
die("Error on mysql query".mysqli_error());
}
else{
$msg="<center><h4><font color='#FF0000'>Congratulation, you have made your vote.</h4></center></font>";
include 'student.php';
exit();
}
}
?>
the errors are at code including
$sess= $_SESSION['SESS_NAME']; and at username="'.$_SESSION['SESS_NAME'].'"
i have tried every possibility so can you check my code?
mainly the error is undefined index at $session[session_name]?
Are you sure the session 'SESS_NAME' is getting set? In the code above you are only trying to access its value. Undefined index is the error thrown when there is no session with that name.
Looks like to me you haven't declared the variable $_SESSION['SESS_NAME']. Try doing the following
var_dump($_SESSION);
This will show you all the defined variables in the session, if SESS_NAME isn't there then it hasn't been defined. Maybe you have failed to define it somewhere else?

Unable to get session in different PHP page

Unable to get session from different PHP page other than where i initialized it
This is my first PHP page where i initialize the session.
<?php
$i =1;
$team = htmlentities($_POST['team']);
$id = htmlentities($_POST['id1']);
$mobile = htmlentities($_POST['mobile1']);
if(isset($_POST['id2']))
{
$ids = htmlentities($_POST['id2']);
$mobiles = htmlentities($_POST['mobile2']);
$i=2;
}
if(isset($_POST['id3'])){
$ids = $ids.','.htmlentities($_POST['id3']);
$mobiles = $mobiles.','.htmlentities($_POST['mobile3']);
$i=3;}
echo $team;
echo $i;
$connect =new mysqli('localhost', 'root', 'password','test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
$data = "INSERT INTO `Users`(`team_name`, `id`, `mobile`, `ids`, `mobiles`) VALUES ('$team','$id','$mobile','$ids','$mobiles')" ;
$createData="CREATE TABLE `$id`(
`id` INT NOT NULL ,
`ansOpChoosen` INT NOT NULL,
`realAns` INT NOT NULL
);";
echo 'pass';
$link ="/test.html";
$link2 = "/signups.html";
if(mysqli_query($connect,$data) && mysqli_query($connect,$createData) )
{
session_start();
$_SESSION['user'] = $id;
header('Location: '.$link);
echo "new record created successfully";
}
else{
header('Location: '.$link2);
echo "error";
}
$connect->close();
?>
This is another php page where i try to retrive data but it doesnt fetch any thing
<?php
$id = $_SESSION['user'];
$quesNo = $_POST['questionNo'];
$optionCho = $_POST['optionchoosen'];
$optionReal =$_POST['optionreal'];
echo $id;
//echo "hbbhkhb";
$connect =new mysqli('localhost','root','password`','test');
if($connect->error){
echo "connection error";
}
$check ="SELECT * FROM `$id` WHERE `id`=$quesNo";
if($res=mysqli_query($connect,$check)){
$count = mysqli_num_rows($res);
if($count>0)
{
$data ="UPDATE `$id` SET `ansOpChoosen`=$optionCho,`realAns`=$optionReal WHERE `id`=$quesNo";
}
else{
$data = "INSERT INTO `$id`(`id`,`ansOpChoosen`,`realAns`) VALUES ($quesNo,$optionCho,$optionReal)";
}
$store=mysqli_query($connect,$data);
}
?>
Put session_start(); at the top of every page that you want to use sessions on.
You always have to call session_start() before doing something with the session.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
Source: http://php.net/manual/en/function.session-start.php
A session is started with the session_start() function.
Be careful : it must be top of every page.
For example :
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Manual : http://php.net/manual/en/session.examples.basic.php

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

storing username from session to database while form submission using php

I have a simple question,
I have a login and workspace area.
After the user logs in It shows the username of the logged in user at workplace as what I wanted. Now my problem is when user finish filling form available in his workspace the form is then stored in database also i need the username that is coming from session also get stored to the database.
here is code that is storing username and maintaining session after user reach at workspace after login:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/MainProject/connect/auth.php');
session_start();
?>
The final version of the updated insert file :
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
// session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>
In the logging in process, you must store your username in a session
$_SESSION['username'] = $username;
in the process of saving the form, you can call session_start(); and get the session using
$tobeinserted = $_SESSION['username'];
I believe
Remove comment in session start.
Use this.
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
//$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>

Retrieving information from database

I am trying to check if the session username matches the record in my database and if it does, I want to include a file.
This is my code
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT * FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez)
{
include('check.php');
}
else
{
echo "error";
}
?>
The session username does not match the record in my database, yet the file is being included. Why?
OH, I FOUND THE ISSUE. IT IS CONSIDERING MY USERNAME TO BE ROOT...BUT WHEN I SAY ECHO $_SESSION['USERNAME'] IT IS CRAIG#CRAIG.COM..WHY SO>
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT sessionusername FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez["sessionusername"]==$username)
{
include('check.php');
}
else
{
echo "error";
}
?>
You are simply testing whether the array $geez is empty or not. If the array has anything in it, you if($geez) will return true. To stop this behaviour, please see ceteras' answer, particularly this part:
if($geez["sessionusername"]==$username)
{
include('check.php');
}
I believe that's the only part that has changed.
Thanks,
James

Categories