PHP/MySQL: Check if username exists - php

I'm a beginner in php and I want to check if the username entered already exists.
Here is my code.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
include "connect.php";
ValidateUser();
}
function ValidateUser()
{
if (!empty($_POST['username']) AND !empty($_POST['password'])) {
$queryrow=mysqli_query("SELECT * FROM websiteusers WHERE username = '$_POST['username']'");
if ($rows=mysqli_num_rows($queryrow)=0) {
RegisterUser();
}
}
function RegisterUser() {
echo "works up to here";
}
?>
It doesn't even give me an error despite turning error reporting on.

Have you even initialized a mysqli_connect?
$Connection = mysqli_connect("host","user","pass","database");
Then pass it to a function which uses mysqli_query() by:
function foo ($DB){
mysqli_query($DB,"QUERY HERE");
// Do other stuff
return /* Whatever you wish to return here*/
}
foo($Connection);

What you are trying to achieve can be done very easily with the following code. A bigger concern is security. It is good practice to both sanitize your input every time the user has a chance to input text.
Also, using prepared query's will put yet another layer of security.
Although this isn't using your provided code directly, I believe it is good to teach good habits.
If you have any questions feel free to ask.
$username = $_POST['username']; <-- sanitize this
$message = null;
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
if ($stmt->num_rows() > 0) {
RegisterUser();
} else {
$message .= 'username already exists';
}
Later on when you require more items to be queried, or more results to be bound:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username); <-- the "s" means the argument is a strings, if a argument is stored as an int use "i", but one character for each argument is required.
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
Multiple Arguments:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=? AND authenticated=?");
$stmt->bind_param('si', $username,$isauthenticated); <-- second argument is a INT or BOOL
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql,$passwordsql,$other1sql,$other2sql);
$stmt->fetch();
When your expecting multiple results, and lets say you want to dump them into arrays:
$userarray = array();
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
while($stmt->fetch()){
array_push($userarray, $usernamesql);
}
$userarray is now an array of all the results fetched from the database.

Here is the right way to do this:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if(check_user($mysqli, $_POST['username']){
registerUser();
}else{
echo 'user exist, cannot register';
}
}
function check_user($conn, $username){
$query = "SELECT * FROM websiteusers WHERE username = ?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->close();
}
return $stmt->num_rows === 0;
}
function registerUser() {
echo "registering user ...";
}
Read up on prepared statement

Related

password_verify having a few issues hopefully someone can help me

So im making a login for a game system that uses a JSON string to read back the files, however when I Hash the password and try login it doesn't work however when the password is unhased it works fine, I think the problem lies with the password verify part.
Im just unsure where to place it if someone could guide me in the right direction that will be amazing...
So the issue is when I send the $password example test5 it only reads as test 5 and not this $2y$10$viov5WbMukXsCAfIJUTUZetGrhKE9rXW.mAH5F7m1iYGfxyQzQwD.
This was the original Code
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
$mysqli->close();
}
Then I tried This
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$GetPassword = "SELECT password FROM users WHERE username='$username'";
$data = mysqli_query($GetPassword);
if(password_verify($password, $data['password'])) {
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
} else {
// password is in-correct
}
$mysqli->close();
}
$data = mysqli_query($GetPassword);
^^^---mysqli result handle/object
if(password_verify($password, $data['password'])) {
^^^^^^^^^^^^---no such element in mysqli
You never fetched your data results, so you're comparing the entered password against a non-existent element of the $data result object/handle.
You need
$row = mysqli_fetch_assoc($data);
password_verify(..., $row['password']);
Most likely you're running with error_reporting and display_errors disabled, meaning you'd never see the "undefined index" warnings that PHP would ave been throwing everytime you ran this code. Those settings should NEVER be off on a devel/debug system.
And note that you're vulnerable to sql injection attacks, so your "security" system is anything but -it's entirely useless and trivially bypassable.
There are several issues with your code, such as:
This statement $data = mysqli_query($GetPassword) is wrong. mysqli_query() expects first argument to be your connection handler, so it should be,
$data = mysqli_query($mysqli, $GetPassword);
Look at this statement, if(password_verify($password, $data['password'])) { ...
mysqli_query(), on success, returns a result set, so you can't get the password using $data['password']. First fetch the row from the result set and then get the password, like this,
$row = mysqli_fetch_assoc($data);
if(password_verify($password, $row['password'])) { ...
Look at the following query,
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
This query won't return any rows because of this WHERE condition, ...password='$password'. So the solution is, instead using two separate queries, use only one query to validate the password and retrieve relevant data. The solution is given down below.
Your queries are susceptible to SQL injection. Always prepare, bind and execute your queries to prevent any kind of SQL injection.
If you want to build a json string then instead of doing echo "{"; echo '"result": "success",'; ..., create an array comprising of all the relevant data and then json_encode the array.
So the solution would be like this:
// your code
$username = $_GET["user"];
$password = $_GET["password"];
// create a prepared statement
$stmt = mysqli_prepare($mysqli, "SELECT username, password, regkey, banned FROM users WHERE username=?");
// bind parameters
mysqli_stmt_bind_param($stmt, 's', $username);
// execute query
mysqli_stmt_execute($stmt);
// store result
mysqli_stmt_store_result($stmt);
// check whether the SELECT query returned any row or not
if(mysqli_stmt_num_rows($stmt)){
// bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password, $regkey, $banned);
// fetch value
mysqli_stmt_fetch($stmt);
if(password_verify($password, $hashed_password)){
echo json_encode(array('result' => 'success', 'regkey' => $regkey, 'banned' => $banned));
}else{
// incorrect password
}
}else{
// no results found
}
mysqli_stmt_close($stmt);
// your code

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Checking if Username and Password are correct

As my code is right now, I always get the echo "Username/Password incorrect."; whether or not the username/password match or not. My question is, What did I do wrong in the code below for the php to always echo "Username/Password incorrect"
<?php
require 'privstuff/dbinfo.php';
$password1 = $_POST["password1"];
$username = $_POST["username"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner#othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("SELECT username, password FROM accounts WHERE username=? and password=?")) {
$db_pw = password_hash($password1, PASSWORD_BCRYPT);
$stmt->bind_param("ss", $username, $db_pw);
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Logged in.";
}else{
echo "Username/Password incorrect.";
}
$stmt->close();
}
$stmt->close();
$mysqli->close();
?>
Update I've changed if ($stmt->affected_rows > 0) to if ($stmt->num_rows). Still doesn't work though
UPDATE 2 I've realized the issue is me using password_hash($password1, PASSWORD_BCRYPT); I didn't realize that the hash gives different strings every time. I'm not understanding on how to use password_verify
The documentation of mysqli_stmt_affected_rows() says:
This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows() instead.
You also need to call mysqli_stmt_store_results() first, to buffer the results.
$stmt->store_results();
if ($stmt->num_rows > 0) {
...
}
I figured it out. I was not supposed to use password_hash again. I didn't realize that using password_hash gave different results. I then changed it to use password_verify.
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `password` FROM `accounts` WHERE username = ?")) {
/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $username);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
if(password_verify($password1, $result))
{
echo("Hello");
}else{
echo("No-Go");
}
$mysqli->close();
?>

Mysqli prepared statements error? [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I've ran into this error with prepared statements, I've just started with prepared statements so go easy on me please, Heres the error:
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in C:\wamp\www\darkhorizons\login.php on line 31
Heres my code:
if (isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(isset($username) && isset($password)) {
$mysqli = new mysqli("localhost","root","","phplogin") or die("Couldnt connect!");
if(mysqli_connect_errno()){
echo "Connection failed: ". mysqli_connect_errno();
exit();
}
if($stmt = $mysqli -> prepare("SELECT * FROM users WHERE username =? AND password =? LIMIT 1")){
$stmt -> bind_param("ss", $username, $password);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> fetch();
$numrows = mysqli_num_rows($result);
} else {
die("Please enter a username and password!");
}
if($numrows == 1){
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true ;
$query = "SELECT adminflag FROM users WHERE username = '{$_SESSION['username']}' LIMIT 1;";
$result2 = mysqli_query($connect, $query);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 == 1) {
$_SESSION['isadmin'] = true;
}
header("Location: {$pageLoc}");
exit(); //It's good to use exit or die (same thing) AFTER using header to redirect
} else {
}
}
}
As a side note, Please ignore any mistakes in the code below the prepared statement, im redoing my login script that ive been using to learn.
Going through your code you didn't really need to query you DB twice, you should read the adminflag in that same select.
SELECT * is never a good idea always select specific fields.
And I also noticed you are using two differnt style, I suggest you to stick to the Object oriented approach.
<?php
if (isset($_POST['submit'], $_POST['username'] , $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli("localhost","root","","phplogin");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT adminflag FROM users WHERE username = ? AND password = ? LIMIT 1";
if ($stmt = $mysqli->prepare($query)) {
$stmt -> bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
printf("Number of rows: %d.\n", $numrows );
if($numrows == 1){
$stmt->bind_result($admin_flag);
$stmt->fetch();
session_start();
if ($admin_flag== 1) {
$_SESSION['isadmin'] = true;
}
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true ;
header("Location: {$pageLoc}");
}else{
echo 'user not found';
}
}
$stmt->close();
$mysqli->close();
}else{
echo 'required field missing';
}
?>

PHP login script issues

I have a couple of questions on my login script. It's just directing me to a blank page with no errors.
If I'm using mysqli, do I need to use ? or $username and $password in
my query?
I don't understand anything going on with $stmt -> fetch(); am I using it right?
$result=mysqli_query($stmt); : does this $result variable contain both the username and password?
If that's the case, how does mysqli_num_rows($result) work?
<?php
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);
/* Create a new mysqli object with database connection parameters */
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT Login_ID, Login_PW,
FROM login
WHERE Login_ID='$username' AND Login_PW ='".md5($_POST['password'])."'"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, $password);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($username, $password);
/* Fetch the value */
while ($stmt->fetch())
{
$result=mysqli_query($stmt);
//Check whether the query was successful or not
if($result)
{//main if
if(mysqli_num_rows($result) == 1)
{
//Login Successful
session_regenerate_id();
$login = mysqli_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $login['Login_ID'];
//$_SESSION['SESS_FIRST_NAME'] = $login['firstname'];
//$_SESSION['SESS_LAST_NAME'] = $login['lastname'];
session_write_close();
header("location: member-index.php");
exit();
}
else {
//Login failed
header("location: login-failed.php");
exit();
}
}
else
{
die("Query failed");
}
}//main if close
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
?>
I was attempting to address each of your questions but, they got so mixed that I couldn't just give you an answer for each. So i took the liberty of modifying your posted script with what i believe will make it work. Perhaps some extra tweaking is still necessary. Please review comments I added inline. Also, review the following php documentation pages for more information on using mysqli functions in its object oriented form:
http://www.php.net/manual/en/mysqli-stmt.num-rows.php
http://www.php.net/manual/en/mysqli-stmt.execute.php
http://www.php.net/manual/en/mysqli-stmt.bind-result.php
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
I haven't tested it and i might have a typo or two, but here is my attempt at improving your script. Let me know what you think:
<?php
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);
/* Create a new mysqli object with database connection parameters */
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Is your username the same as the login_id? If not you need to change this query's where to use the username column not the login_id. */
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("
SELECT Login_ID, firstname, lastname
FROM login
WHERE Login_ID=? AND Login_PW=?
"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, md5($password));
/* Execute it */
$result = $stmt -> execute();
//Check whether the query was successful or not
if ($result === false) {
die("Query failed");
}
/* Bind results to variables that will be used within the fetch() loop. */
$stmt -> bind_result($login_id, $firstname, $lastname);
/* Check the number of rows returned. */
if ($stmt->num_rows !== 1) {
//Login failed
header("location: login-failed.php");
exit();
}
/* Iterate over the results of the query. */
while ($stmt->fetch())
{
//Login Successful
session_regenerate_id();
/* We can use $login_id, $firstname and $lastname cause we binded the result to those variables above. */
$_SESSION['SESS_MEMBER_ID'] = $login_id;
//$_SESSION['SESS_FIRST_NAME'] = $firstname;
//$_SESSION['SESS_LAST_NAME'] = $lastname;
session_write_close();
header("location: member-index.php");
exit();
}//main if close
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
?>
When you're using a prepared statement, you normally shouldn't substitute variables into the statement. You put ? placeholders there, and then use $stmt->bind_param() to associate these placeholders with variables.
After using $stmt->fetch(), you can reference the variables that you bound with $stmt->bind_result to access the results of the SELECT.
You shouldn't be using mysqli_query at all if you're using a prepared statement. To answer your question about how it works, $result doesn't contain the actual data. You call something like $row = mysqli_fetch_assoc($result) to get the username and password into $row.
You should use $stmt->num_rows()
I am sorry friend i don't know much about mysqli.
But this can be easily done with mysql if you want.
By the way, for your 3rd question,
$result=mysqli_query($stmt); returns only the resource id's if there is any matching records for your search criteria. and mysqli_num_rows($result); will return how many resource id's are available for that criteria.username and password will only returned after mysqli_fetch_array($result); that will make the database to fetch the record as an array for those resource id's.
hope you understand...:))
I think, the problem is with this part of your code
while ($stmt->fetch())
{
$result=mysqli_query($stmt);
You have executed the statement, and fetched it; there is no need for you to query it again . . . . I'm not familiar with mysqli as I use PDO, but I think since you binded the result to $username, $password you can access the returned values with these binded variables.
while ($result = $stmt->fetch())
{
if($result->num_rows == 1)
{
$_SESSION['SESS_MEMBER_ID'] = $result['LOGIN_ID']
//////or $_SESSION['SESS_MEMBER_ID'] = $username
You can proceed like this, I think . . .

Categories