Undefined index: userID error - php

Upon Logging in, I have the userID stored in the SESSION. However when I call updateMarkerlocations.php it says userID is undefined. Not sure what I'm missing.
login.php
session_start();
if (!isset($_POST['submit'])){
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from userinfo WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
$row = $result->fetch_assoc();
setcookie("username", time() +60*60*24*30*365);
$_SESSION['userID'] = $row['userID'];
echo "<p>Logged in successfully!, Please close the window</p>";
}
}
?>
updateMarkerLocations.php
<?php
include 'db_const.php';
function insertMarkerLocations()
{
$markerCount = 0;
if (isset($_POST['markerCount']))
$markerCount = $_POST['markerCount'];
if(isset($_SESSION["userID"]))
{
$userID = $_SESSION["userID"];
}
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$userID = $_POST['userID'];
for($i=0 ; $i < $markerCount; $i++){
$index = $i;
++$index;
$curMarkerID = $_POST["markerID$index"];
$curLang = $_POST["lang$index"];
$curLat = $_POST["lat$index"];
// Now write the current marker details in to the db.
$query = "INSERT INTO userinfo (userID, markerID, lang, lat ) VALUES ('$userID', '$curMarkerID', '$curLang', '$curLat')";
mysql_query($query)
or die(mysql_error());
}
$msg = "SUCCESS";
return $msg;
}
$msg = insertMarkerLocations();
echo json_encode($msg);
?>

Add this at the top of each file:
if(!isset($_SESSION)) session_start();
Also, when you do:
$userID = $_POST['userID'];
you should ensure that $_POST['userID'] exists:
if(isset($_POST['userID'])) $userID = $_POST['userID'];

Related

php sqlsrv connection by multiple servers to one specific database

So I have 3 servers(192.168.0.21 , 192.168.0.22 and 192.168.0.23) and I would like them to connect to a database called Pensions they are all using sql server (UID and PWD)authentication. Is it possible to achieve this using php and sqlsrv_connect()? This the connect.php:
<?php
#first start session
session_start();
// session time out after no activity for 4 minutes
if ($_SESSION['TimeOut'] + (5 * 60) < time()) {
// session timed out
header("Location: ./sessdestroy.php");
exit;
} else {
// store new request time.
$_SESSION["TimeOut"] = time();
}
function getConnection(){
$db = 0;
if(!$_SESSION['Database']){
$db = 0;
}else{
$db = $_SESSION['Database'];
}
$databaseName = 'Pension';
if ($db == 0)
{ // Country A
$serverName ='192.168.0.21';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else if($db ==1)
{ // Country B
$serverName ='192.168.0.22';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else
{ //Country C
$serverName ='192.168.0.23';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
//connection string
//echo "test here...";
//echo " S: ".$serverName." u: ".$UID." P: ".$PWD;
$serverName = "serverName";
$connectionInfo = array( "Database"=>"$databaseName", "UID"=>"$UID", "PWD"=>"$PWD");
$conn = sqlsrv_connect($serverName,$connectionInfo);
//exit();
//phpinfo();
if (!$conn)
{
exit("Connection Failed: " . $conn);
//try local server
if ($db == 1) {
$serverName ='192.168.0.20';
$UID ='fund_user';
$PWD ='fund_user';
$databaseName = 'Pension';
$conn = sqlsrv_connect($serverName,$connectionInfo);
if (!$conn) return 0;
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
return 0;
}
else
{
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
}
?>
Then this is the process.php (when a connection is established it leads the user to a homepage depending on the user role )
<?php
//give no error
ini_set("display warning",0);
#include connection
include('Connections/fundmaster.php');
if(!isset($_SESSION))
{
session_start();
}
//temp store for the database session before destory
$db = 0;
$db = $_SESSION["Database"];
if ($db==""){
$db = 0;
}
if (!isset($_SESSION["Database"]))
{
$_SESSION["Database"] = 0;
}
$_SESSION["Database"] = $db;
if($_POST['subLogin'])
{
$nationalID = $_POST['sname'];
$PWD = $_POST['Memberno'];
$conn = getConnection();
$sql = "select * from netlogin where NationalID = '";
$sql .= $nationalID ."' and vcPassword= '" .$PWD."'";
$sql = stripslashes($sql);
$stmt = sqlsrv_query($sql, $conn);
if($row = sqlsrv_fetch_array($stmt)){
$SchemeNo = $row[0];
$MemberNo = $row[1];
$userRole = $row[6];
session_start();
if (!isset($_SESSION["SchemeNo"]))
{
$_SESSION["SchemeNo"] = $SchemeNo;
}
if (!isset($_SESSION["MemberNo"]))
{
$_SESSION["MemberNo"] = $MemberNo;
}
if (!isset($_SESSION["userRole"]))
{
$_SESSION["userRole"] = $userRole;
}
$_SESSION["SchemeNo"] = $SchemeNo;
$_SESSION["MemberNo"] = $MemberNo;
$_SESSION["userRole"] = $userRole;
$_SESSION["Database"] = $db;
if($userRole == "1"){
header("Location:admin/adminarea.php");
}else{
header("Location:membersarea.php");
}
}else{
header("Location: login.php");
}
}else{
header("Location: login.php");
}
?>

Error while outputting sessions in other page

I created a login page in PHP with session. everything is going well. but when i try to output the session in other page. it giving me NOTICE
Notice: Undefined variable: email in C:\xampp\htdocs\COIN Website\test5.php on line 81
Notice: Undefined variable: email in C:\xampp\htdocs\COIN Website\test5.php on line 82
Notice: Undefined variable: email in C:\xampp\htdocs\COIN Website\test5.php on line 84
I don't know whats wrong. Actually, I am new to PHP.
here is the login page
<?php
session_start();
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "coins";
$con = mysqli_connect("$servername", "$username", "$password","$db_name");
$email = mysqli_real_escape_string($con, $_POST['email']);
$eth = mysqli_real_escape_string($con, $_POST['eth']);
if (empty($email) || empty($eth)) {
header("Location: home.php?Login=Empty_fields");
exit();
} else{
$sql = "SELECT * FROM users WHERE email='$email' ";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: home.php?Login=user_does_not_exist");
exit();
}
else {
$check = mysqli_query($con, "SELECT email FROM users WHERE eth='$eth'");
if (mysqli_num_rows($check) >= 1) {
$_SESSION['email'] = $row['email'];
$_SESSION['eth'] = $row['eth'];
header("Location: pow.php?Login=Success");
} else {
header("Location: home.php?Login=invaild_email_or_eth address");
}
}
}
}else {
header("Location: home.php?Login=Error");
exit();
}
?>
and the other page code
if (isset($_POST['submit'])) {
$servername = "localhost";
$user = "root";
$password = "";
$dbname = "coins";
// Create connection
$conn = new mysqli($servername, $user, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$_SESSION['email'] = $email;
echo $email;
$sql = "INSERT INTO profile (email, action_points)
VALUES ('$email' , '0.003')";
if ($conn->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
You can try like this. you are doing wrong with get session variable value.
<?php session_start();
// check session
if(isset($_SESSION['email']))
{
$email = $_SESSION['email'];
// Now you can do your stuff
}
else
{
echo "session not set for email";
die;
}

Can't fetch rows from MySQL database

I'm a bit rusty on mysql, especially now that it's mysqli... Nothing happens in the script below, the variables $row[username] etc are empty. What am I doing wrong?
<?php
session_start();
include_once('./db_config.php');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5(mysqli_real_escape_string($conn, $_POST['password']));
$query = "SELECT * FROM players WHERE username = '".$username."' AND password = '".$password."'";
if($res = mysqli_query($conn, $query))
{
$row = mysqli_num_rows($res);
$_SESSION['Username'] = $row['username'];
$_SESSION['uID'] = $row['id'];
$_SESSION['Join_Date'] = $row['join_date'];
mysqli_free_result($res);
header('Location: ../index.php');
} else
{
echo mysqli_error($conn);
}
?>
You are not fetching the records instead you are doing myql_num_rows(this will give only no of record)
use this to fetch records
$row = mysqli_fetch_array($res,MYSQLI_ASSOC);
<?php
session_start();
include_once('./db_config.php');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5(mysqli_real_escape_string($conn, $_POST['password']));
$query = "SELECT * FROM players WHERE username = '".$username."' AND password = '".$password."'";
if($res = mysqli_query($conn, $query))
{
$row = mysqli_fetch_array($res,MYSQLI_NUM);
$_SESSION['Username'] = $row['username'];
$_SESSION['uID'] = $row['id'];
$_SESSION['Join_Date'] = $row['join_date'];
mysqli_free_result($res);
header('Location: ../index.php');
} else
{
echo mysqli_error($conn);
}
?>

Checking if username is available

I am trying to check if the username is available before i insert into the table.
But it seems to insert into the table no matter if the username already exists.
Here is my php code:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'myPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$email = $_POST['email'];
$username = mysqli_real_escape_string($link,$username);
$password = mysqli_real_escape_string($link,$password);
$name = mysqli_real_escape_string($link,$name);
$email = mysqli_real_escape_string($link,$email);
$password = md5($password);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count > 0) {
$sql = "INSERT INTO mainLogin (username, password, name, email) VALUES ('$username', '$password', '$name','$email' )";
$result = mysqli_query($link, $sql);
if (!$result) {
die('Error: ' . mysqli_error($link));
}else {
$_SESSION['login'] = $username;
echo "<script>window.location = 'http://madsanker.dk.linux101.unoeuro-server.com'</script>";
}
}else {
echo "username taken";
}
mysqli_close($link);
?>
What am I doing wrong?
just change the greater sign in your if statement from ">" to ==0
if($count==0){
}
If username already in db than change this condition:
if($count > 0) { 
//your stuff
}
With:
if($count <= 0) { // if not found
//your stuff
}

Ajax post json response issue

I have an issue with ajax response. I am using custom query for fetch result from database. Json response always shows null value while query is running successfully. Here is my code:
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
while($fetch = mysql_fetch_array($query))
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
#Amandhiman i did not get what is the use of if statement with in the while
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
the mention code definitely works for you
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
Try with the below code, (mysql is deprected), working for me with my test database table (Debug it, var_dump $result, $result->fetch_assoc(), $result->num_rows)
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
try this
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
echo json_encode($arr);
}
First of all start session before playing with it on the top of page
session_start();
check your database connectivity.
Use print_r($arr) for testing your array();
first off all you are using session variable . to use session variable you need to initialize it by session_start()
you are using key in the array in this way it will return the last inserted record in the array . try this code
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
// if wants to use session then start session
session_start(); // else it will return null
$_SESSION['ID']= $fetch['id']; // i don't know why this ??
// $arr['id'] = $_SESSION['ID']; comment this
$arr[] = array('msg'=>'succsee','ID'=>$fetch['id']);
}
else
{
$arr[]= array('msg'=>'fail','ID'=>null);
}
}
echo json_encode($arr);
}

Categories