Unable to fetch and compare mysql data in php - php

I want to check if the 'desig' (designation) of a user stored in user_info database, is 'gm' (G.M.) or not.
Currently, I have two users, one with 'desig' as 'gm' and the other as 'mgr', no matter who logs in, the 'gm.html' page always loads.
The correct working should be that if the desig is gm then only it should redirect to gm.html page. (members is a table in user_info db)
<?php
session_start();
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {echo "";}
else{
header("location:login.html");}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$desig = mysqli_fetch_array($result) or die("error");
if($desig!="gm")
{
$mysql_db1='customer';
$con1=mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db1) or die("Connection died for your sins.");
echo "Connected";}
else
header("location:gm.html");
?>

Your code seems to be hard-coded to only return a GM?
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
I am pretty sure that this is supposed to be picked up based on the user and not simply running a "find me a GM user" for anyone.
If I understand your question correctly, shouldn't there be somewhere in betwen the start and end of this snipped that uses the login information to verify what level a user is it?
if((isset($_SESSION['login']) && $_SESSION['login'] ==true))
{
echo "";
// Shouldn't you run a query here to see who your user is?
// For example to get their ID?
}
else
{
header("location:login.html");
}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
// Then here, instead of running this, convert it to something similar to:
$result = mysqli_query($con, "SELECT desig FROM members WHERE userid=$id");
Edit:
Storing the variable is easy - but you have to GET it from somewhere.
You can do this by popping a column in your users table - where you verify the username and password to begin with. I would suggest you look into a basic table like this to store user information. (I would also recommend you store hashes of passwords and the like, but that seems a conversation for another time).
user table:
userID username password userLevel
1 someUser somePass Grunt
2 someUser1 somePass1 MGR
3 someUser2 somePass2 MGR
4 someUser3 somePass3 GM
Armed with this, you can fire off a quick query to the database, verify the username and password, and get their userLevel quite easily.
Once you have the level, you can store it in a session variable if you like and have your code apply logic depending on what is stored in there.

I fixed the problem. There were some logical errors in my code.
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {
//Selecting the whole row to compare and display different variables
$sql = "SELECT * FROM members WHERE username = '".$_SESSION['username']."'";
if(!$sql)
echo mysql_error();
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//Using $row variable to fetch and compare the value stored in 'desig' with 'gm'
if($row["desig"]=='gm')
header("location:gm.php"); //Opens up different page for gm aka Gen. Mgr.
}
else
header("location:login.html"); //Redirects to this page if no user is logged in.

Related

display database info on next page after loggin in using session

I'm new to PHP and I'm going to try to explain it the way I could :D. I'm trying to accomplish when the user logged in (using username and password), it opens a new page with the users name, address etc.
In my database table, I have a username, password, name and address.
I was able to accomplish the login page using session but would like to how to get/fetch those information like name and address to the new page it opens.
Thank you,
MD :)
correct me if i'm wrong.
Here is how u fetch the information from a certain table by using PHP and MySQL(PhpMyAdmin) database.
$conn = mysqli_connect("localhost", "root", "", "hotel"); //Connecting to the database
if($conn){
$sql = "SELECT USER_NAME, USER_PASS FROM USER"; //SELECT statement
$result = $conn->query($sql); //Executing the statement
if(mysqli_query($conn, $sql)){ //If query success
while($row = $result->fetch_assoc()){ //While loop to retrieve all data
$user = $row["USER_NAME"]; //Assign Column USER_NAME in database to $user
$pass = $row["USER_PASS"]; //Assign Column USER_PASS in database to $pass
echo $user."</br>".$pass."</br>"; //Displaying the content
}
}else{
echo "Query failed";
}
}else{
die("Fatal Error");
}
$conn->close(); //Close the database connection

Can someone explain PHP SQL Select data to me?

I want to select the password data of a user so they can log in on my website (for a member only website). I have a hash of the password and the username written to a table called "users" upon account creation. I do not know how to select a row on the table, so I get the error when the code looks for, something?
I found this on w3, but I don't understand what each part of the code means.
I tried to edit the code so it would match my user case, but I don't know how to.
$servername ="127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$dbname = "users";
//create connection to db
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
$sql = "SELECT id, username, password FROM users";
$result == $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row == $result->fetch_assoc()) {
echo $userid = $row["id"] && $serverpassword = $row["password"] && $serverusername = $row["username"];
}
} else {
echo "User Lookup Failed";
}
$conn->close();
You don't need to select all records from database and then iterate all of them to check correct user. Besides, you should only select user by username and password as below:
$sql = "SELECT id, username, password FROM users WHERE username = '".$serverusername."' AND `password` = '".serverpassword."' ";
Apart, you should use data binding instead of variable to avoid SQL injection.

MSQLI Having Trouble with num_rows

I am having trouble returning the number of rows. I want my code to check if a username exists, and if it does then return an error. The way I am going about this is if num_rows returns a number larger than 0. I haven't implemented that part yet, I am just trying to get it to return the number of rows right now. Here is my current code:
$hostname = ''; //SET SERVER/HOSTNAME
$dbusername = ''; //SET DATABASE USERNAME
$dbname = ''; //SET DATABASE NAME
$dbpassword = ''; //SET DATABASE USERNAME
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link)
{
$systemerror = 'Connect Error' . mysqli_connect_errno() . mysqli_connect_error();
$error = "there has been an error";
}
$sql = "SELECT username FROM affiliates WHERE username = $username";
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT);
if (!result)
{
$error = "There was an error with our system. Please contact All Choice Dental or wait a few minutes. Thank you.";
goto error;
}
$row_cnt = $result->num_rows;
echo $row_cnt;
I don't even get zero back for num_rows, so something has to be wrong. I know I can connect to the database, because I can Insert rows using the same connection.
$username is never defined in your code, so the query comes out as
SELECT username FROM ... username =
As well, since a username is likely to be a string, you're also lacking quotes around that variable, so even if it was set, the query would still be wrong. e.g.
$username = 'fred';
would produce
SELECT username FROM affiliates WHERE username = fred
and you're not likely to have a fred field in your affiliates table. The field should be quoted:
SELECT username FROM ... WHERE username = '$username';
and you should seriously consider using prepared statements instead, as this sort of construct is vulnerable to SQL injection attacks.
You're mixing MySQLi OOP and Procedural - which is bad coding style.
To get the number of rows procedurally, use mysqli_num_rows($result)

MySQL Value as PHP Session

I have a registration script where the user id is saved as a session variable after registration and the user is redirected to their homepage. For some reason the user id is not being stored in the session variable. This exact same script worked on a different project, I simply took the project and changed the database connection settings and now it's not working.
Here is the registration script:
mysqli_connect($db_host, $db_user, $db_pass) OR DIE (mysqli_error());
// select the db
mysqli_select_db ($link, $db_name) OR DIE ("Unable to select db".mysqli_error($db_name));
// our sql query
$sql = "INSERT INTO seekers (first_name, last_name, username, email, password, salt) VALUES ('$firstName', '$lastName', '$username', '$email', '$hashedPW', '$salt');";
//save the updated information to the database
$result = mysqli_query($link, $sql) or die("Error in Query: " . mysqli_error($link));
if (!mysqli_error($link)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['user_id'] = mysqli_insert_id($link);
$_SESSION['loggedin'] = TRUE;
header("Location: ../index.php");
}
And here is the session checking and db query on the protected page:
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['user_id'] != 'user_id') {
include_once('includes/user.header.php');
//set user_id
$user_id = $_SESSION['user_id'];
//include the logged in user header
include_once('includes/user.header.php');
//select user information according to their logged in user_id
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
$row = mysqli_fetch_assoc($sql);
//create piece name together
$firstName = $link->real_escape_string($row['first_name']);
$lastName = $link->real_escape_string($row['last_name']);
$fullName = $firstName. " " .$lastName;
//get username
$username = $link->real_escape_string($row['username']);
When I am redirected to the index.php page, everything looks fine, except none of the user information is being queried from the DB.
Can anyone see what is wrong here? I know it's got to be something little and I'm just over looking it.
Please any help would be greatly appreciated.
EDIT: All information is being stored in the database successfully as well.
You are trying to use user_id without a select query ... indeed you must get the last insert id
changed line ;
$_SESSION["user_id"]=mysql_insert_id();
and
if (!mysqli_error($link))
should be
if (!mysqli_error($result))
and
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
to
$sql = $link->query('SELECT * FROM seekers WHERE user_id = "'.$user_id.'"');

mysql - fetching data from table row

I have gotten a snippet of code to bring back the username and password and see if they match. i now want to set a session varaible to the 'points' value i have in the table which is in the same row as the username and pass.. what could be done?
<?php $username="asdin";
$password="1sdA2";
$database="a75sdting";
$pword = $_REQUEST['pword'];
$uname = $_REQUEST['uname'];
mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
$exsists = 0;
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
break;
}
if ($exsists){
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}
mysql_close();
?>
i want to set $_SESSION['points'] = $row[points] i guess... but i dont think that is correct
<?php
// start session (required on every page that uses sessions
session_start();
// db auth
$username="asdin";
$password="1sdA2";
$database="a75sdting";
// user auth
$pword = $_POST['pword']; // should use either $_POST or $_GET, NOT $_REQUEST
$uname = $_POST['uname']; // should use either $_POST or $_GET, NOT $_REQUEST
// open db connection
$conn = mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database,$conn) or die( "Unable to select database");
// check user
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
if(mysql_num_rows($query)){
// user exists
$row = mysql_fetch_assoc($query);
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}else{
header('Location: http://wwsdipts/login.php'); // take them back to login page if incorrect details
}
// close db connection
mysql_close($conn);
?>
I've tidied up your code a bit, please take a look at the notes. It is also worth nothing the following:
You should be using some sort of protection against SQL injections, such as mysql_real_escape_string($_POST['uname']) - the same for password
You need session_start() on all pages that use session variables
You shouldn't use $_REQUEST, use either $_POST or $_GET (read about it)
Do you actually have a table named username? You should read up a bit about DB design, a better name/use for this table would be users as the table will be holding users (a combination of unique ID, username & password.
I don't know what you mean about points, but to access any column name in the "username" table, use $row['column-name'] after it is set ($row = mysql_fetch_assoc($query);)
If you intend on using PHP a lot in the future, you should look up PDO, it's a great class for handling SQL.
you are right, but in this case your array is rows, and it should be in
$_SESSION['points'] = $rows['points']
And it should be in your while loop:
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
$_SESSION['points'] = $rows['points']
break;
}
However, it might be better to do something like this:
if(mysql_num_rows($result) == 1) {
//Login Successful
rows = mysql_fetch_assoc($result);
$_SESSION['points'] = $rows['points']
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}

Categories