Stored Procedure for Login Authentication not working MySQL - mysql

I am working Login Authentication with Stored Procedures in MySQL Database.
Below is the code, i wrote but its not working. Let me know, what is wrong.
I have below questions
How to check, whether CURSOR is empty or null
Is there any way, we write the procedure.
What I am doing..
Taking two input parameters and two parameters for ouput.
Check if the user or password is not valid, stored those values in OUT parameters
SELECT 'Invalid username and password', 'null' INTO oMessage, oUserID;
If user and password in valid, but isActive column is 0 then
SELECT 'Inactive account', 'null' INTO oMessage, oUserID;
If success,
SELECT 'Success', v_UserID INTO oMessage, oUserID;
SQL Code
DELIMITER $$
USE `acl`$$
CREATE
DEFINER = `FreeUser`#`localhost`
PROCEDURE `acl`.`checkAuthenticationTwo`(
IN iUsername VARCHAR(50),
IN iPassword VARCHAR(50),
OUT oMessage VARCHAR(50),
OUT oUserID INT
)
BEGIN
DECLARE v_isActive INT;
DECLARE v_UserID INT;
DECLARE v_count INT;
DECLARE cur1 CURSOR FOR SELECT UserID, IsActive FROM m_users WHERE (LoginName = TRIM(iUsername) OR Email = TRIM(iUsername)) AND `Password` = iPassword;
OPEN cur1;
SET v_count = (SELECT FOUND_ROWS());
IF (v_count > 0)
FETCH cur1 INTO v_UserID, v_isActive;
IF (v_isActive = 0) THEN
SELECT 'Inactive account', 'null' INTO oMessage, oUserID;
ELSE
SELECT 'Success', v_UserID INTO oMessage, oUserID;
END IF;
ELSE
SELECT 'Invalid username and password', 'null' INTO oMessage, oUserID;
END IF;
END$$
DELIMITER ;

You definitely don't need CURSORs for that; use plain simple SELECT. A more concise version of your SP might look like
DELIMITER $$
CREATE DEFINER = `FreeUser`#`localhost` PROCEDURE `acl`.`checkAuthenticationTwo`
(
IN iUsername VARCHAR(50),
IN iPassword VARCHAR(50),
OUT oMessage VARCHAR(50),
OUT oUserID INT
)
BEGIN
SELECT CASE WHEN IsActive = 0 THEN 'Inactive account' ELSE 'Success' END,
CASE WHEN IsActive = 0 THEN NULL ELSE UserID END
INTO oMessage, oUserID
FROM m_users
WHERE (LoginName = TRIM(iUsername)
OR Email = TRIM(iUsername))
AND `Password` = iPassword
LIMIT 1; -- you better protect yourself from duplicates
SET oMessage = IFNULL(oMessage, 'Invalid username and password');
END$$
DELIMITER ;
What it does it tries to select a row where username or email equals to iUsername and password equals to iPassword and outputs two values to output variables. Along the way it uses CASE to look at isActive value. If it's 0 then sets a message to 'Inactive' and NULL for userid. Otherwise it returns 'Success' message and real userid that has been found. Now, if a user has not been found both variables will be set to NULL. We can leverage that and use IFNULL() function to detect that fact and set a message to 'Invalid username and password'.
Here is SQLFiddle demo
Personally I'd go further and simplify it a bit more and make it a one-statement SP with the following interface:
Returns:
userid (which is > 0) if a user with username and password if found
0 - username and(or) password incorrect
-1 - a user is inactive
The idea is that it's a presentation layer's task to produce appropriate messages for the user and not scatter all those message literals across data layer.
CREATE DEFINER = `FreeUser`#`localhost` PROCEDURE `acl`.`checkAuthenticationThree`
(
IN iUsername VARCHAR(50),
IN iPassword VARCHAR(50),
OUT oUserID INT
)
SET oUserID = IFNULL(
(
SELECT CASE WHEN IsActive = 0 THEN -1 ELSE UserID END
FROM m_users
WHERE (LoginName = TRIM(iUsername)
OR Email = TRIM(iUsername))
AND `Password` = iPassword
LIMIT 1 -- you better protect yourself from duplicates
), 0);
Here is SQLFiddle demo

Related

How stored procedure output instead of rows count?

My stored procedure always returns 0. I tried unique data and duplicated but the insert is done with success but the return value is always the same #new_identity = 0
CREATE PROCEDURE [dbo].[spAddAuthor]
#Author tyAuthor READONLY,
#new_identity INT = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- check if the author exists
IF NOT EXISTS (SELECT Id_Author FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM #Author)
OR dbo.Authors.phone = (SELECT phone FROM #Author)
OR dbo.Authors.email = (SELECT email FROM #Author)))
BEGIN
INSERT INTO dbo.Authors (Username, sexe, email, phone, address)
SELECT [Username], [sexe], [email], [phone], [address]
FROM #Author
-- output the new row
SELECT #new_identity = ##IDENTITY;
END
ELSE
BEGIN
-- get the author Id if already exists
SELECT #new_identity = (SELECT TOP 1 Id_Author
FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM #Author)
OR dbo.Authors.phone = (SELECT phone FROM #Author)
OR dbo.Authors.email = (SELECT email FROM #Author)))
END
END
I found that in the declaration of the parameters I put null beside the output and that what caused the problem.
#new_identity INT = NULL OUTPUT
but I don't understand why, I thought the 'null' was like the default value, or when you try to make the parameter optional you add null as default value.
can someone explain, please?

Parameter name conflict with column name in MySQL

The following code works fine when put it outside a function and return 1 if it exists at the table.
SET #Result = (SELECT (
CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = 'username') THEN 10
ELSE 1
END) r);
SELECT #Result;
But it returns 10 when I am passing the value 'username' to a function like below
CREATE DEFINER=`root`#`localhost` FUNCTION `FN_CheckUsername`(
Username VARCHAR(128)
) RETURNS int
READS SQL DATA
BEGIN
SET #Result = (SELECT (
CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = Username) THEN 10
ELSE 1
END) r);
RETURN #Result;
END
Please try naming your username parameter to the FN_CheckUsername function something other than Username:
CREATE DEFINER=`root`#`localhost` FUNCTION `FN_CheckUsername`(uname VARCHAR(128))
RETURNS int
READS SQL DATA
BEGIN
SET #Result = (SELECT (
CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = uname)
THEN 10 ELSE 1 END) r);
RETURN #Result;
END
The parameter and column name could be masking each other, which would result in the exists clause always being true.

how do I check if firstname does not exists in mysql procedure

How do I check if the firstname is not filled and I've tried not null like this:
DELIMITER go
Create procedure registerusers(
Out UserID tinyint(11),
IN iFirstName varchar(30),
IN iLastName varchar(30),
IN iPassword varchar(30),
IN iEmailAddress varchar(30),
IN iSalt varchar(40),
IN iRoleID varchar(1))
BEGIN
/* I've used not null and it works for empty firstname but when I
try to pass the firstname it didn't work and I kept getting an error message saying "fill out the firstname" */
If(iFirstName not null) then
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Fill out the First Name ';
else
insert into users(
/* insert into user if its not empty */
FirstName,
LastName ,
Password ,
EmailAddress ,
Salt ,
RoleID
)
Values
(
iFirstName,
iLastName ,
iPassword ,
iEmailAddress ,
iSalt ,
iRoleID
);
set UserID = last_insert_id();
end if;
End
go
DELIMITER ;
However when I used
set #new_id = null;
call registerusers(#new_id,'','Jones','5566','jones#gmail.com','sdfd','1');
select #new_id;
it manages to display an error message but when I used
set #new_id = null;
call registerusers(#new_id,'Jason','Jones','5566','jones#gmail.com','sdfd','1');
select #new_id;
for inserting the firstname it kept displaying an error message other than wanting to insert the data.
I've tried if(firstname is null) but it didn't work because it went pass through message. For example if I used
set #new_id = null;
call registerusers(#new_id,'','Jones','5566','jones#gmail.com','sdfd','1');
select #new_id;
as empty for firstname it went through and it suppose to display an error message. If I used
set #new_id = null;
call registerusers(#new_id,'Jason','Jones','5566','jones#gmail.com','sdfd','1');
select #new_id;
it manages to go through.

mysql stored function simple login, extract int from set

this is my first mySQL stored-function 'cause i've always managed such things with php.
I want a function that checks if a user can log in my client-area.
I wrote the code above:
DELIMITER $$
CREATE FUNCTION `A05`.`login` (user VARCHAR(64),pass VARCHAR(64)) RETURNS INT
BEGIN
declare num_rows int;
declare id int;
SELECT (#num_rows:=COUNT(*)),(#id:=`Credential_id`) FROM `A05`.`Credentials` where `Credential_UserName` = user;
if num_rows = 0 then
-- user not present
return (-1);
end if;
-- user present, checking password
SELECT (#num_rows:=COUNT(*)),(#id:=`Credential_id`) FROM `A05`.`Credentials` where `Credential_id` = id AND `Credential_PASSWORD` = SHA1(pass);
if num_rows = 0 then
-- user presente, password incorrect
INSERT INTO `a05`.`Events` (
`Event_id` ,
`Event_RegistrationDate` ,
`Event_VariationDate` ,
`Event_State`,
`Event_Notes`,
`Event_SenderId`,
`Event_Type`
)
VALUES (
NULL , NOW(), NOW(), 'wp', NULL, id, 1
);
return (-2);
end if;
-- user present, password correct
UPDATE `A05`.`Credentials` SET `Credential_LastAccess`=NOW() where `Credential_id` = id;
INSERT INTO `a05`.`Events` (
`Event_id` ,
`Event_RegistrationDate` ,
`Event_VariationDate` ,
`Event_State`,
`Event_Notes`,
`Event_SenderId`,
`Event_Type`
)
VALUES (
NULL , NOW(), NOW(), 'ok', NULL, id, 0
);
return id;
END
I think that the syntax should be right except for the last statement return id cause i return a set instead of an integer.
The problem is that when i try to store this function on mysql i get this error:
Error 1415: Not allowed to return a result set from a function
Then i changed the last statement from 'return id' to 'return 0' for testing purpose but i keep getting the same error.
Probably is a newbie error cause it's the very first time for me on sql "advanced" scripting.
Thank you very much in advance!

MySQL - Error 1064 in Stored Proc SQL

I have written the following stored procedure which in HeidiSQL is giving me an Error 1064 at the line starting with SET pay_ref = SELECT CONCAT('KOS' ...
Let me firstly explain what's going on with this procedure. I have a table gamers with a BIGINT primary key with auto_increment. This proc is supposed to:
Take in some params from the user
Check if the user already exists in the db according to his/her email address, and spits back the word "DUPLICATE" if a reord does exist
Else it does the insert as normal
Then it reads in the ID of the new record created and converts it to a varchar, pads it with leading zeros and then gets concatenated with some other strings
This new string (which should read for example KOS00001ABCDEF) then gets updated to the pay_refcode field >>> this is how we have settled on generating a unique payment reference for the user
If all works out well it updates retval with the newly generated reference code to be read by PHP script.
DELIMITER //
CREATE PROCEDURE `InsertGamer` (
IN p_fname VARCHAR(30),
IN p_lname VARCHAR(30),
IN p_email VARCHAR(255),
IN p_favgame VARCHAR(60),
IN p_pay_suffix VARCHAR(6),
OUT retval VARCHAR(14)
)
BEGIN
DECLARE last_id BIGINT;
DECLARE pay_ref VARCHAR(14);
IF (EXISTS(SELECT * FROM gamers WHERE (email = p_email))) THEN
SET retval = 'DUPLICATE';
ELSE
INSERT INTO gamers (fname, lname, email, favgame, pay_refcode)
VALUES (p_fname, p_lname, p_email, p_favgame, NULL);
SET last_id = LAST_INSERT_ID();
SET pay_ref = SELECT CONCAT('KOS', (SELECT LPAD(CONVERT(last_id, VARCHAR(5)),5,'0')), p_pay_suffix);
UPDATE gamers
SET pay_refcode = pay_ref
WHERE application_id = last_id;
SET retval = pay_ref;
END IF;
END //
I cannot for the life of me figure out what the problem is and would sincerely appreciate any help from you. Thank you very much in advance!
You just need to remove the SELECT keyword from line which you set the value for pay_ref.
SET pay_ref = CONCAT('KOS', LPAD(CONVERT(last_id, CHAR(5)),5,'0'), p_pay_suffix);
full code:
DELIMITER //
CREATE PROCEDURE `InsertGamer` (
IN p_fname VARCHAR(30),
IN p_lname VARCHAR(30),
IN p_email VARCHAR(255),
IN p_favgame VARCHAR(60),
IN p_pay_suffix VARCHAR(6),
OUT retval VARCHAR(14)
)
BEGIN
DECLARE last_id BIGINT;
DECLARE pay_ref VARCHAR(14);
SET #count := (SELECT COUNT(*) FROM gamers WHERE email = p_email)
IF (#count > 0) THEN
SET retval = 'DUPLICATE';
ELSE
INSERT INTO gamers (fname, lname, email, favgame, pay_refcode)
VALUES (p_fname, p_lname, p_email, p_favgame, NULL);
SET last_id = LAST_INSERT_ID();
SET pay_ref = CONCAT('KOS', LPAD(CONVERT(last_id, CHAR(5)),5,'0'), p_pay_suffix);
UPDATE gamers
SET pay_refcode = pay_ref
WHERE application_id = last_id;
SET retval = pay_ref;
END IF;
END //
DELIMITER ;