Would someone be able to give me a MySQL relation query for looking up a column value of a table based off of another value of the same table?
For instance, I have a table with 4 columns (id, name, email, password). How could I look up the the value of the "id" column of a certain user based off of their email in the "email" column and store the result (id) in a variable?
Here's the session() controller function
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');
if (databaseContainsAuthor($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['authorid'] = $author;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['authorid']);
$GLOBALS['loginError'] =
'The specified email address or password was incorrect.';
return FALSE;
}
}
I've tried
SELECT id FROM article WHERE email='$email'
Is there a more efficient way to do it? I'm also not totally sure how to store the result of the query in the $author session variable.
Thanks in advance.
Your query is perfect (with the proviso that you are sanitising the $email variable - see the tale of Little Bobby Tables).
SELECT id FROM article WHERE email='$email'
And to perform that query and set the variable $author to the returned value is simply:
$author = 0;
if( ( $idFromEmail = #mysql_query( "SELECT id FROM article WHERE email='".mysql_real_escape_string( $email )."'" ) )
&& mysql_num_rows( $idFromEmail )==1
&& ( $r = mysql_fetch_assoc( $idFromEmail ) ) ){
$author = $r['id'];
}
Rewritten in long form, if the above is too complex to follow:
$author = 0;
if( !( $idFromEmail = #mysql_query( "SELECT id FROM article WHERE email='".mysql_real_escape_string( $email )."'" ) ){
// SQL Query Failed
}elseif( mysql_num_rows( $idFromEmail )!=1 ){
// More than, or less than, one row returned
}else{
$r = mysql_fetch_assoc( $idFromEmail );
$author = $r['id'];
}
Related
For my website I need to be able to get an ID from a database after someone logged in. I already figured out how to put the variables from the login page into a session but I cant figure out how to write a code that gets an ID from a database and turns it into a session variable.
session_start();
include( "connection.php" );
if(isset($_GET['action']) && ($_GET['action'] == "login")){
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$pass = mysqli_real_escape_string($conn, md5( $_POST['pass'] . "90qdjka*#"));
$QUERY = "SELECT * FROM users WHERE username = '$name' AND password = '$pass' AND enabled = 1";
$EXEC = mysqli_query($conn, $QUERY );
if(mysqli_num_rows($EXEC)==0){
die( 'Login niet geldig! Opnieuw inloggen' );
}else{
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
$QUERY = "UPDATE users SET lastlogin=NOW() WHERE username = '$name' AND password = '$pass'";
mysqli_query($conn, $QUERY);
}
}
?>
else{
if (mysqli_num_rows($EXEC) > 0) {
while($row = mysqli_fetch_assoc($EXEC)) {
$_SESSION['id'] = $row["id"];
}
}
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
if your query returns only one result then while loop will run only one time but if your query returns more than one record then the last record's id will be stored in your session variable
In $row["id"], id is the column name of the table, if you are selecting all columns from your table and if your users table has columns like name, username, password then you can access it using $row["name"], $row["username"], $row["password"]
I've created a login activity and there are two edittext ids and passwords. I have a PHP code which checks the user with their id and password. If both are correct then it transfers to the other activity, but here I want a PHP code which checks the id with their specific password. If the user enters a correct id but enters an incorrect password, then it should produce an error "pls enter correct password".
Please suggest me a correct PHP code for this.
<?php
require "r_connect.php";
if($_SERVER['REQUEST_METHOD']=='POST')
{
$rollno=$_POST['rollno'];
$password=$_POST['password'];
$sql = "SELECT * FROM registration_user WHERE rollno = '$rollno' AND password='$password'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo 'Success';
}
else
{
echo 'Error';
}
}
?>
Try below code for PHP:
<?php
require "r_connect.php";
if($_SERVER['REQUEST_METHOD']=='POST')
{
$rollno = $_POST['rollno'];
$password = $_POST['password'];
$sql = "SELECT password FROM registration_user WHERE rollno = '$rollno'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
if(mysqli_num_rows($check) > 0)
{
if($check["password"] == $password){
echo 'Success';
}else{
echo 'pls enter correct password';
}
}
else
{
echo 'Invalid id';
}
}
?>
You can also refer this tutorial for more information
Split your SQL statement into to, at first query WHERE rollno = '$rollno', if found go on and query WHERE rollno = '$rollno' AND password = '$password', if everything's correct go on, if first statement fails user is not found, if second query fails, the user is found but password is not matching, this is your desired case.
When writing an authentication flow you can keep following things in mind :
validate your input data well
when interacting with Select queries use prepared statements whenever possible
use sha1 and md5 combinations on the password string to store in the database and comparisons.
I have tried to implement these things in the following code, of course there's always scope for improvement
function checkRollno($conn, $rollno)
{
$stmt = mysqli_stmt_init($conn);
$prepareQuery = "SELECT count(*) FROM tablename WHERE rollno = ?";
//Prepared Statements
if( mysqli_stmt_prepare($stmt, $prepareQuery ) )
{
// Bind params
mysqli_stmt_bind_param($stmt, 'i', $rollno);//i is for integer
/* execute query */
mysqli_stmt_execute($stmt);
/* Fetch Result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
/* close statement */
mysqli_stmt_close($stmt);
if( count($row) < 1 )
return false;
else
return true;
}
else
return false;
}
function checkUserExists($conn, $rollno, $pass)
{
$stmt = mysqli_stmt_init($conn);
$prepareQuery = "SELECT count(*) FROM tablename WHERE rollno = ? AND password= ?";
//Compare sha1 of md5 of your password (You should not store or check against exact password strings)
$pass = sha1(md5($pass));
//Prepared Statements
if( mysqli_stmt_prepare($stmt, $prepareQuery ) )
{
// Bind params
mysqli_stmt_bind_param($stmt, 'is', $rollno, sha1(md5($pass)));// s is for strings
/* execute query */
mysqli_stmt_execute($stmt);
/* Fetch Result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
/* close statement */
mysqli_stmt_close($stmt);
if( count($row) < 1 )
return false;
else
return true;
}
else
return false;
}
//Main Block
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if( isset($_POST['rollno']) && $_POST['rollno'] != '' )
$rollno = $_POST['rollno'];
if( isset($_POST['password']) && $_POST['password'] != '' )
$pass = $_POST['password'];
$res = checkRollno($conn, $rollno);
if( $res )//rollno exists
{
if( checkUserExists( $conn, $rollno, $pass ) )
die('authenticated');//Authenticated
else
die('denied');//Wrong password
}
else//rollno doesn't exist
{
//code to reflect wrong id does not exist
}
}
I am sure you can use better function names :)
Prepared Statements
Your code could look like this :
$sql = "SELECT * FROM registration_user WHERE rollno = '$rollno'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
Then you can do checks :
if(mysqli_num_rows($check) > 0)
{
if($check['password']===$password){
//id and pass correct
}else{
// id correct , but bad password
}
}else
{
echo 'Invalid id';
}
I have made a login system which enables a user to sign in using a previously defined email and password, however in the testing section, I have noticed the passwords say they don't match although I know they are correct as I wrote the test one down as I made it. I cant seem to see why this is happening, I think it may be something to do with my hashing of the passwords but I don't know what.The login page check is from document, login.php:
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$data['email']]);
if(!$row = $stmt->fetch())
{
// email didn't match
$errors['login'] = "Login failed. on email";
}
else
{
// email matched, test password
if(!password_verify($data['password'],$row['password']))
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The insertion to the database with hashing is, from insert.php:
if (isset($_POST['name'])){
$name = $_POST['name'];
}
if (isset($_POST['email'])){
$email = $_POST['email'];
}
if (isset($_POST['password'])){
$pword = $_POST['password'];
}
if (isset($_POST['busName'])){
$busName = $_POST['busName'];
}
if (empty($name)){
echo("Name is a required field");
exit();
}
if (empty($email)){
echo ("email is a required field");
exit();
}
if (empty($pword)){
echo("You must enter a password");
exit();
}
$pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
//insert html form into database
$insertquery= "INSERT INTO `cscw`.`users` (
`accountID` ,
`businessName` ,
`name` ,
`emails` ,
`password`
)
VALUES (
NULL , '$busName', '$name', '$email', '$pword'
);";
and on the web page i am shown from login.php, "Login failed. on password". If you need to see any more code please let me know.
It does not recognize $row['password'].
Be always organized with your query **
1)Prepare
2)Execute
3)Fetch
4)Close
5)THEN YOU EXPLOIT the fetched data.
The fetched data need to be sorted as shown with the returnArray function.
Hoping that there are UNIQUE emails and the $data array exists.Try this.
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=:emails";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':emails', $data['email']);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->CloseCursor();
$stmt=null;
/* Return the results is a more handy way */
function returnArray( $rows, $string )
{
foreach( $rows as $row )
{
return $row[ $string ];
}
}
if( empty($rows) )
{ // email didn't match
$errors['login'] = "Login failed. on email";
}
else
{ // email matched, test password
if( !password_verify( $data['password'], returnArray($rows,'password') ) )
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The login Page is not finished the query is not inserting. Be carefull you might be vunerable to SQL injections because your do not escape user manipulated variables.(To strengthen security add a form validation, it will be great).
You have used $pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
I removed ."/n" part. I seems that you are using a concatenation operator '.' to add /n add the end of the password_hash.
Your $insertquery is not finished and not readable. You don't need to insert backticks in your query. And no need to SELECT accountID it will autoincrement (See if A_I for accountID is ticked in your database).
Do something like this in your login page.
/* trim and escape*/
function escapeHtmlTrimed( $data )
{
$trimed = trim( $data );
$htmlentities = htmlentities( $trimed, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' );
return $htmlentities;
}
if ( isset( $_POST['name'] ) ){
$name = escapeHtmlTrimed( $_POST['name'] );
}
if ( isset($_POST['email']) ){
$email = escapeHtmlTrimed( $_POST['email'] );
}
if ( isset($_POST['password']) ){
$pword = escapeHtmlTrimed( $_POST['password'] );
}
if ( isset($_POST['busName']) ){
$busName = escapeHtmlTrimed( $_POST['busName'] );
}
if ( empty($name) ){
echo("Name is a required field");
exit();
}
if ( empty($email) ){
echo ("email is a required field");
exit();
}
if ( empty($pword) ){
echo("You must enter a password");
exit();
}
/*Remove this your adding "./n"*/
$pword = password_hash($pword, PASSWORD_DEFAULT);
//insert html form into database
$insertquery= "INSERT INTO users (businessName ,name ,emails,
password) VALUES (:busName , :name, :email , :pword)";
$stmt = $pdo->prepare($insertquery);
$stmt->bindParam(':busName', $busName);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':pword', $pword);
$stmt->execute();
$stmt->CloseCursor();
$stmt=null;
I hello I am currently trying to add data to my user login database however for some reason my database it not being updated when I register a new user.
here is my code from user.inc.php:
<?php
//checks if username already exists in database
function user_exists($user)
{
$user = mysqli_real_escape_string($user);
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= ('$user')");
return (mysql_result($total, 0) == '1') ? true : false;
}
//checks if username and password combo is valid
function valid_credent($user, $pass)
{
$user = mysqli_real_escape_string($user);
$pass = sha1($pass);
$total = mysqli_query("SELECT COUNT user_id FROM users
WHERE user_name = '$user' AND
user_password = '$pass' ");
return(mysql_result($total, 0) == '1') ? true : false;
}
//add user to database
function add_user($user, $pass)
{
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$queryStr = "INSERT INTO users (user_name, user_password) VALUES ('$user', '$pass')";
$R = mysqli_query($mysqli,$queryStr);
}
?>
I also have warning on my register page when I try to add view errors
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/PostalCloud/core/user.inc.php on line 8
line 8:
return (mysql_result($total, 0) == '1') ? true : false;
I have tried using "sanitize()" however that doesn't exists.
UPDATE: Still getting errors after modifying code. Here part of my register.php code and I have a init.inc.php that uses mysqli to connect to database.
<?php
include('init.inc.php');
$errors = array();
if(isset($_POST['username'], $_POST['password'], $_POST['repeatPassword']))
{
if(empty($_POST['username']))
{
$errors[] = 'The username cannot by empty. ';
}
if(empty($_POST['password']) || empty($_POST['repeatPassword']))
{
$errors[] = 'The password cannot by empty. ';
}
if($_POST['password'] !== $_POST['repeatPassword'])
{
$errors[] = 'Password verification failed. ';
}
if(user_exists($_POST['username']))
{
$errors[] = 'The username you entered is already taken. ';
}
if(empty($errors))
{
add_user($_POST['username'], $_POST['password']);
$_SESSION['username'] = htmlentities($_POST['username']);
header('Location: protected.php');
die();
}
}
?>
init.inc.php:
<?php
session_start();
$exceptions = array('register', 'login');
$page = substr(end(explode('/',$_SERVER['SCRIPT_NAME'])), 0, -4);
if(in_array($page, $exceptions) === false)
{
if(isset($_SESSION['username']) === false)
{
header('Location: login.php');
die();
}
}
$mysqli = mysqli_connect('localhost','root','', 'user_system');
$path = dirname(__FILE__);
include("{$path}/core/user.inc.php");
?>
The problem is that mysql_query() is returning a boolean instead of a result resource. There are two reasons this can happen:
You performed query that returns success/fail instead of a result
set (e.g. UPDATE)
Your query failed
your query contains single quotes on column names..this should be removed :
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= '$user'");
I have created a registration form ( see code below ). There are two fields for the password, the second serving as a check and upon form submission I check if the input in the fields matches. If they don't a message is successfully sent that the passwords do not match but the new user record is still inserted into the database. How can I prevent record insertion if the password fields do no match?
Here is the code:
<?php
$username = isset( $_POST["username"] ) ? $_POST["username"] : "";
$password = isset( $_POST["password"] ) ? $_POST["password"] : "";
$confirm = isset( $_POST["confirm"] ) ? $_POST["confirm"] : "";
if( !empty( $username ) && !empty( $password ) ) {
if( $password != $confirm )
header( "location:registration.php?msg = Password does not be match." );
$host = "localhost";
$user = "i have put my username here";
$pass = "i have put my pass here";
$link = mysql_connect( $host,$user,$pass ) or die( mysql_error() );
mysql_select_db( "web_db",$link );
$query = "SELECT * FROM users WHERE username = '".mysql_escape_string( $username )."'";
$result = mysql_query( $query );
$count = mysql_num_rows( $result );
if( $count = = 1 ) {
header( "location:registration.php?msg = username already exists" );
} else {
$qry = "INSERT INTO users( username,password )VALUES( '".mysql_escape_string( $username )."', '".mysql_escape_string( $password )."' )";
mysql_query( $qry );
echo "You are successfully registered.";
}
mysql_close( $link );
} else {
header( "location:registration.php?msg = Username or password cannot be blank." );
}
Try this:
if($password != $confirm){
header("location:registration.php?msg=Password does not be match.");
exit;
}
else {
// rest of the code goes here
}
if ($password != $confirm) {
header("location:registration.php?msg=Password does not be match.");
exit();
}
Try using the above code it might help.