Trying to store session variable from result of SQL query - php

I have tried everything from storing the query as a variable and using the fetch_array but it keeps just giving me the output "Array" when I try to print $_SESSION['permission']. I have no idea what to do please help.
<?php
session_start();
mysql_connect("localhost","","");
mysql_select_db("a");
if(isset($_SESSION['loggedin']))
{
header("Location: http://www.mywebsite.com/whatever");
}
if($_POST['submit'])
{
$name = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);
$mysql = mysql_query("SELECT * FROM users WHERE name = '{$name}' AND password = '{$pass}'");
$result = mysql_query("SELECT permission FROM users WHERE name = '{$name}' AND password = '{$pass}'");
$permission = mysql_fetch_array($result);
if(mysql_num_rows($mysql) < 1)
{
die("Password was incorrect!");
}
$_SESSION['loggedin'] = "YES";
$_SESSION['name'] = $name;
$_SESSION['permission'] = $permission;
header ("Location: http://www.mywebsite.com/whatever");
}
echo "<form type='login.php' method='POST'>
Username: <br>
<input type='text' name='username'><br>
Password: <br>
<input type='password' name='password'><br>
<input type='submit' name='submit' value='Login'>
</form>";
?>

You need to traverse the resultset using a loop,
while($row = mysql_fetch_array($result)) {
//use each row value($row) as per your need
}
So, I believe, you want to achieve something like this,
if(isset($_POST['submit']))
{
$name = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);
$result = mysql_query("SELECT permission FROM users WHERE name = '{$name}' AND password = {$pass}'");
$permission = mysql_fetch_array($result);
$mysql = mysql_query("SELECT * FROM users WHERE name = '{$name}' AND password = '{$pass}'");
if(mysql_num_rows($mysql) < 1)
{
die("Password was incorrect!");
}
$_SESSION['loggedin'] = "YES";
$_SESSION['name'] = $name;
$i = 0;
while($row = mysql_fetch_array($result)) {
$_SESSION['permission' . $i] = $row;
$i++;
}
header ("Location: ");
}

If $row is a result of a query you need to specify a column like $_SESSION['permission'] = $row[column_name];

Just edited the POST part of your code. Remember that you must fetch the result and use the associative array to take the value of an specific column:
if($_POST['submit'])
{
$name = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);
$result = mysql_query("SELECT * FROM users WHERE name = '{$name}' AND password = {$pass}'");
if(!$row = mysql_fetch_array($result))
{
die("Password was incorrect!");
}
$_SESSION['loggedin'] = "YES";
$_SESSION['name'] = $name;
$_SESSION['permission'] = $row['permission'];
header ("Location: ");
}
There is no need to run the query twice.

You are assigning the row array to the $_SESSION['permission'] variable so when you print it you get array.
Try using print_r on that array and you'll see what's in it. Example: print_r($_SESSION['permission']); Print cannot print an array. Use print_r or var_dump to find out what's going on when you see this happen again.
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.print-r.php

Related

how to retrive data from database using mysqli_fetch_array in php

How can retrive data.here login not working.I used mysqli_fetch_array,but before while the condition failed.
<?php
session_start();
include 'db.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM tbl-login where username='".$username."'");
$n = 0;
while($row = mysqli_fetch_array($query)) {
// $u-id = $row['u-id'];
$dbusername = $row['username'];
$dbpassword = $row['password'];
$usertype = $row['usertype'];
$_SESSION['usname'] = $dbusername;
$_SESSION['uid'] = $u-id;
$_SESSION['usertype'] = $usertype;
if ($dbusername == $username && $dbpassword == $password) {
$n++;
echo "grtet";
// header('location:dashboard.php');
}
}
if ($n == 0) {
header('location:index.php');
}
?>
$query = mysqli_query($connect,"SELECT * FROM tbl-login where username='".$username."' and password='".$password."'");
$row = mysqli_fetch_row($query); // Just ONE row, because expecting is, there is only one user with this USERNAME
if(empty($row)) {
echo 'Invalid username or password';
}else{
echo 'OK :)';
}
When you're not sure what makes a query fail, call mysqli_error(). While I haven't tested myself, I believe tbl-login is the cause of the error (which mysqli_error() should return if you call it).
MySQL allows spaces and non-identifier characters to be table/column name, but when referring to such a name, you need to enclose it between backtick (`). Hence tbl-login should be written as `tbl-login` in the SQL query.
You Have Created table name as tbl-login, column name as u-id and variable as $u-id, which i think is a problem. If Possible, change your column name, table name and variable name. Here are some links to get basic idea for creating variable name, column name, table name.
Create Variables, Create Table, Identifiers
I've updated your code. Please have a look.
<?php
session_start();
include 'db.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM `tbl_login` WHERE username='$username' AND password='$password'");
$rowcount = mysqli_num_rows($query);
if($rowcount > 0) {
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$_SESSION['usname'] = $row['username'];
$_SESSION['uid'] = $row['u_id'];
$_SESSION['usertype'] = $row['usertype'];
header('location:dashboard.php');
}
} else {
header('location:index.php');
}
?>

Php - Two-Way Login Form [Admin & User]

I am trying to make a login form which is able to detect whether the user is admin or non-admin. I tried the following but when i run it i get no results:
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$r = mysqli_fetch_array($a);
if(is_array($row))
{
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
}
elseif(is_array($r))
{
$_SESSION["admin"] = $row[id];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
?>
When i insert the username and password for admin it reloads the login form.
UPDATE 1:
The non-admin part is just working fine but the admin part redirects/reloads itself to the login form.
you should check your login post form,should have a code like this:
<form name="loginform" method="post" action="check.php">
if your 'action' vlaue is invalid,the page may refresh.
you should confirm that your login form is posted to the php page you posted.
Try this, lets see what happens.
session_start();
$msg = "";
if(count($_POST)>0){
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$stdCount = mysqli_num_rows($result);//counts the number or rows returned from student table
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$tchrCount = mysqli_num_rows($a);// same but with teachers table
if($stdCount != 0){
$row = mysql_fetch_array($result);
$_SESSION['id'] = $row['id']; //set session for non admin.
}else if($tchrCount != 0){
$r = mysql_fetch_array($a);
$_SESSION['admin'] = $r['id'];
}else{
echo "Username and Password is not Matching.";
}
}//end of the main if
I have not tested this code so dunno if it works or not but I think you got the logic.
use quotes: $row["id"]
"Location: " must be capital.
after calling the "header" function make sure you use "exit".
This code is not tested, but if I understood correctly, should work.
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result_student = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_student = mysqli_fetch_array($result_student);
$result_teacher = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_teacher = mysqli_fetch_array($result_teacher);
if(is_array($result_student))
{
$_SESSION["id"] = $row_student["id"];
$_SESSION["name"] = $row_student["name"];
$_SESSION["admin"] = 0;
}
elseif(is_array($result_teacher))
{
$_SESSION["id"] = $row_teacher["id"];
$_SESSION["name"] = $row_teacher["name"];
$_SESSION["admin"] = $row_teacher["id"];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
if(#$_SESSION["admin"]>0)
{ header ("Location: gui-admin.php");
exit;
}
else
{ header("Location: user_dashboard.php");
exit;
}
}
?>
Hope it helps....
But I can guess why you are facing the problem for your code only working for students.
In this -
if(is_array($row))
is_array($row) would always be returning true and the code goes on to execute
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
but $row[id] would be empty because there are no rows matching the criteria, so $_SESSION["id"] would not be assigned and when this is executed -
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
None of the if statements would not be executed because none of them are set. This is my analysis. This could be wrong.
Try the solution below -
You should combine the users table for just querying whether the user is a student or a teacher. You then query the student table or the teacher table depending on the Main "Users" table. Querying for the same username and password to two tables doesnt look good.
You can change the meta tag in my code to header("Location: $url") but I would prefer this so that the request doesnt get cached by the user.
Hope it helps :-
$sql="SELECT * FROM {$table} WHERE username='{$username}' and password='{$password}'"; //My variables are already filtered and safe from SQL Injection.
$result=mysqli_query($mysqli, $sql);
if(mysqli_num_rows($result))
{
$fetch=mysqli_fetch_row($result);
$_SESSION["id"]=$fetch['userid'];//Just fetching all details
$_SESSION["Name"]=$fetch['name'];//and making session variables for that.
$_SESSION["username"]=$fetch['username'];
$isadmin=$fetch['isadmin']; //is a BOOL value in MySQL table.
if($isadmin) //checking whether admin or not
{
$_SESSION["isadmin"]=1;
echo "<meta http-equiv='refresh' content='0;url=adminurl'>"; } //if admin redirect to different url
else{
$_SESSION["isadmin"]=0;
echo "<meta http-equiv='refresh' content='0;url=userurl'>";
}
}
else
{
//Username Password Incorrect
/* Show FORM HERE */
}
First of all, you have to know that's really a bad idea to use your POST data directly in your SQL request, you have to avoid that and to clean your data using a function like mysqli_real_escape_string. Also, you have to secure your passwords and avoid to save it clear into your DB, for that take a look on the best way to store password in database.
For your two SQL requests, you can use mysqli_multi_query like I did in this example where I used the same script to get POST data and show the login form :
<?php
if(count($_POST) > 0){
session_start();
$link = mysqli_connect('localhost', 'user', 'pass', 'db');
if(mysqli_connect_errno()) {
die('db connection error : ' . mysqli_connect_error());
}
function secure_password($password){
// secure your password here
return $password;
}
// escape special characters
$user_name = mysqli_real_escape_string($link, $_POST['user_name']);
// you have to secure your passwords, when saving it of course
$password = secure_password(mysqli_real_escape_string($link, $_POST['password']));
$query = "SELECT id FROM student WHERE name = '".$user_name."' and password = '".$password."';";
$query .= "SELECT id FROM teacher WHERE name = '".$user_name."' and password = '".$password."'";
$is_teacher = FALSE;
if(count($_SESSION)) session_destroy();
// you can use mysqli_multi_query for your two requests
if (mysqli_multi_query($link, $query)) {
do {
if ($result = mysqli_store_result($link)) {
if ($row = mysqli_fetch_row($result)) {
if($is_teacher){
$_SESSION['admin'] = $row[0];
} else {
$_SESSION['id'] = $row[0];
$_SESSION['name'] = $user_name;
}
}
mysqli_free_result($result);
}
if (mysqli_more_results($link)) {
// if we have more results, so it's a teacher record
$is_teacher = TRUE;
}
} while (mysqli_more_results($link) && mysqli_next_result($link));
}
mysqli_close($link);
if(isset($_SESSION['id']))
{
header('Location:user_dashboard.php');
}
elseif(isset($_SESSION['admin']))
{
header('Location:gui-admin.php');
}
// no redirection, show the message and the login form
echo 'Invalid Username or Password!';
}
?>
<form action='p.php' method='post'>
User name : <input type='text' name='user_name'><br>
Password : <input type='password' name='password'><br>
<input type='submit' value='Submit'>
</form>
Hope that can help.

mysql_fetch_array() value does not display

if (isset($_POST["username"]) && isset($_POST["password"])) {
$adminuser = $_POST["username"];
$password = $_POST["password"];
// Connecting to database
include "../StorageScript/connecttomysql.php";
//sql query
$sql = mysql_query("SELECT id FROM admin WHERE username='$adminuser' AND password= '$password' LIMIT 1");
$existCount = mysql_num_rows($sql);
while ($row = mysql_fetch_array($sql)) {
$id = $row["id"];
}
$_SESSION['id'] = $id;
$_SESSION['adminuser'] = $adminuser;
$_SESSION['password'] = $password;
}
In the above code am trying to fetch the user id from the database and place it into a session variable. When i try to echo the $_SESSION['id'] in a different page it does not display any thing. But When i try to echo the username it work.
If you use this command mysql_fetch_array($sql) use $row[0].
while ($row = mysql_fetch_array($sql)) {
$id = $row[0];
}
Or if you want to use $row["id"] then use mysql_fetch_assoc($sql)
while ($row = mysql_fetch_assoc($sql)) {
$id = $row["id"];
}
Of course you should be using mysqli_* or PDO rather than the deprecated mysql_* functions.
You want only one row from the query..
So don't use while loop....
if (isset($_POST["username"]) && isset($_POST["password"])) {
$adminuser = $_POST["username"];
$password = $_POST["password"];
// Connecting to database
include "../StorageScript/connecttomysql.php";
//sql query
$sql = mysql_query("SELECT id FROM admin WHERE username='$adminuser' AND password= '$password' LIMIT 1");
$existCount = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
$id = $row['id'];
$_SESSION['id'] = $id;
$_SESSION['adminuser'] = $adminuser;
$_SESSION['password'] = $password;
}

Log in and run query based on a select value

Im trying to use a select box to run different sql to log the user into my site. But for some reason it doesnt work. It "just shows the This user does not exist, please register first if you wish to continue message" that i have at the end.
My plan was just to get the value by using $_POST and storing it in a variable and then just say if that equals this then run this sql to change the value of $databpass and $databuser. (See code for more)
Also for some reason the first if statement works and i can log in. I tried else if but that was the same.
All Help Appreciated thx :D
Please bare in mind that i am fairly new to stackoverflow and php
$username = $_POST ['Username'];
$password = $_POST ['Password'];
$c= $_POST ['ch'];
if ($c=="S")
{
include 'connect.php';
$squery = mysql_query("SELECT * FROM S WHERE Username='$username'" );
$snumrow = mysql_num_rows($squery) or die(mysql_error());
if ($snumrow!=0)
{
while($row = mysql_fetch_assoc($squery)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($c=="Or")
{
include 'connect.php';
$oquery = mysql_query("SELECT * FROM O WHERE Username='$username'" );
$onumrow = mysql_num_rows($oquery) or die(mysql_error());
if ($onumrow!=0)
{
while($row = mysql_fetch_assoc($oquery)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($c== "C")
{
$query = mysql_query("SELECT * FROM C WHERE Username='$username'" );
$numrow = mysql_num_rows($query) or die(mysql_error());
if ($numrow!=0)
{
while($row = mysql_fetch_assoc($query)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($username==$databuser&&$password==$databpass)
{
$_SESSION['username']=$username;
setCookie("sessionUsername", $username, time()+ 3600);
header("Location: memberprofile.php");
}
else
echo "Incorrect pass";
}
else
die("This user does not exist, please register first if you wish to continue");

Retrieve data from database using session variable

<?php
{
session_start();
include "dbconnect.php";
$email = $_SESSION['email'];
echo $email;
$query = "SELECT uid FROM master WHERE emailid = '$email' ";
$result = mysql_query($query);
$row=mysql_fetch_array($result);
while($row)
{
$uid=$row[1];
echo $uid;
}
}
whats wrong in this code.it is giving the email but not able to retrieve uid using session variable email.
please help
while($row) {
$uid = $row[1];
echo $uid;
}
should be
while($row) {
$uid=$row['uid'];
echo $uid;
}
Try if this code works for you
session_start();
include "dbconnect.php";
$email = $_SESSION['email'];
//echo $email;
$query = "SELECT uid FROM master WHERE emailid = '$email' ";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
$uid=$row['uid'];
echo $uid;
}
I don't know why you have { at beginning of your code, you should delete that. And second thing, delete echo $email; and you should have working code
try $uid=$row[0] instead of $uid=$row[1];
Because $row is an array.Array always starts its counter form 0.
here you have defined $uid=$row[1] which means it will display the result from second row of the result set..But there is no second row there is only one row which is "uid" so try $uid=$row[0] instead of $uid=$row[1];
try this:
<?php
session_start();
include "dbconnect.php";
$email = $_SESSION['email'];
$query = "SELECT uid FROM master WHERE emailid = '".$email."'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($result);
$uid = $row["uid"];
echo $uid;
}
else
{
echo "No record found";
}
?>

Categories