Mysql 5.7 checking user credentials via PHP - php

i am beginner in PHP and MySQL. I am trying validate user inputs (Username and Password) in MySQL 5.7 DB but no chance. Let me explain my problem;
I created a user in firstdb with username: firstuser password: firstpassword via phpMyAdmin page.
CODE (check_user-pass.php)
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="rootpassword"; // Mysql password
$db_name="firstdb"; // Database name
$tbl_name="mysql.user"; // Table name
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Define $username and $password
$myusername=$_POST['EMail'];
$mypassword=$_POST['Password'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = mysqli_real_escape_string($conn,$_POST['EMail']);
$mypassword = mysqli_real_escape_string($conn,$_POST['Password']);
$sql="SELECT * FROM $tbl_name WHERE user='$myusername' and authentication_string='$mypassword'";
$result = $conn->query($sql);
$count = 0;
// Mysql_num_row is counting table row
if ($result = mysqli_query($conn, $sql)) {
/* determine number of rows result set */
$count = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $count);
/* close result set */
mysqli_free_result($result);
}
// If result matched $username and $password, table row must be 1 row
if ($count==1) {
echo "Success! $count";
} else {
echo "Unsuccessful! $count";
}
ob_end_flush();
?>
Code return: Connected successfullyResult set has 0 rows. Unsuccessful! 0
If i remove this line: and authentication_string='$mypassword'Code return: Connected successfullyResult set has 1 rows. Success! 1
I succesfully retrieve user inputs from index.php to check_user-pass.php but there is no clear password column in mysql.user table for matching in database.
I search over net and find; password column changed to authentication_string in 5.x but this column carry the hashed thing. So i can't match the user password with this.
Question 1
Should i create a table and store the username and clear password for every user in DB for validating?
Question 2
If question1 answer is NO, how can achieve this validation problem?

I've done so many logins for people I just wrote a class for myself, its on github if you're interested
https://github.com/wazimshizm/secure-login
for easiest out of the box authentication, use this for storing & comparing passwords:
password_hash($passwordVariable, PASSWORD_DEFAULT);
password_verify($inputPassword, $storedPassword);

Related

How To Delete a Specific User from Database?

Let's say I have an user registered on my website and they now want to delete the account.
I've a query to do that but every time the user uses this functionality the code deletes all users.
Here is my code:
<?php
// starts session
session_start();
// set values
$DB_SERVER = 'localhost';
$DB_USERNAME = 'root';
$DB_PASSWORD = '';
$DB_NAME = 'acoolname';
// creates a new connection to the database
$conn = new mysqli($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
// checks connection
if ($conn->connect_error) {
die("ERRO: Falha ao conectar. " . $conn->connect_error);
}
// query to delete the user
$sql = "DELETE FROM users WHERE id = id";
// logout user
if ($conn->query($sql) === true) {
header("location: logout.php");
}else {
echo "ERRO: Falha ao conectar. " . $conn->error;
}
// close connection
$conn->close();
?>
id = id always returns true, so the query indeed deletes all the users.
The safe way to delete a specific user is to use prepared statements, in order to avoid SQL injection.
Something like
$stmt = $conn->prepare('DELETE FROM users WHERE id = ?');
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
Your WHERE condition compares for each row whether the id for the current row matches the id. In other words, the queries compares the field with itself which yields truefor every row. Therefore every row gets deleted.
You have to replace the second id with either a variable that contains the id-value for the current user, or with the id for the current user. The latter is susceptible for SQL injection. See this question how to insert parameters into the query, safely.

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.

Unable to fetch and compare mysql data in 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.

Redirect to a different page based on role in a database

I'm new to PHP. I'm trying to create a login page that will redirect to different pages based on their roles. they will login with staff id and password.
Below are my database
Staff_id password Role
XXX XXX XXX
My HTML login page ---> Login.html
My php code for login --> Login2.php
I've seen other questions n solutions but I still can't get it right. When I log in, it just direct me to an empty page -xx/xx/Login2.php'. What did I do wrong?
I'm using PHP 5.**.
These are my php code:
// Connect to server and select databse.
$db= new mysqli("$host", "$username", "$password");
//check connection
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
// username and password sent from form
$staff_id=$_POST['staff_id'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$staff_id = stripslashes($staff_id);
$password = stripslashes($password);
$staff_id = mysql_real_escape_string($staff_id);
$password = mysql_real_escape_string($password);
$sql="SELECT ROLE FROM $tbl_name WHERE STAFF_ID=$staff_id and PASSWORD='$password'";
$rslt= $db -> query($sql);
// Mysql_num_row is counting table row
$count= $db -> affected_rows;
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$row = mysqli_fetch_array($rslt, MYSQLI_ASSOC);
switch($row["ROLE"])
{
case 'ADMIN':
header("location: /test/HTMLPages/Admin-register.html");
break;
case 'MANAGER':
header("location: /test/HTMLPages/View-report.html");
break;
default:
echo "Wrong staff ID or password";
}
}
?>
Know that I take others code and patch it up as logically as I can.
EDIT: Fixed. of course it would go nowhere because i didn't state the database name. :D
thank u for ur time :D
you select ROLE but as you saied you wrote Role in the DB, you need to write the SAME way you wrote the atrr in the table, and like Fred saied in the comments, it goes the same way in the $row['Role']
switch($row["Role"]){
}
$sql="SELECT Role FROM {$tbl_name} WHERE STAFF_ID={$staff_id} and PASSWORD={$password}";
i dont know if you not included $tbl_name, but from the code above it seems like you have no $tbl_name variable

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)

Categories