Question

Alright so here is my mysql function

DELIMITER $$

CREATE DEFINER=`root`@`%` FUNCTION `password_reset_request`(spUsername VARCHAR(120)) RETURNS varchar(255) CHARSET utf8
BEGIN
    DECLARE vcode VARCHAR(255);
    DECLARE muid INTEGER;
    SET vcode = "test";

    select id into muid from scheme.users where username=@spUsername limit 1;

    RETURN muid;

    IF muid is null THEN
        RETURN 'BADUSER';
    ELSE
        insert into `password_reset`(`uid`,`code`) 
            values ( muid,vcode)
        ON DUPLICATE KEY UPDATE
            `code`=vcode;
        RETURN vcode;
    END IF;
END

Problem I have is that muid is always null. I've even replaced all muid with @muid, which didn't change the outcome.

When I run select id from scheme.users where username=@spUsername limit 1; and replace @spUsername with the same value I'm passing into the function, it gives me the right info.

I've also put in RETURN @spUsername to verify that that variable is set correctly, and it is.

Any ideas? Probably doing something dumb.

Table Schemes

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(120) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `vcode` varchar(120) NOT NULL,
  `isverified` bit(1) DEFAULT b'0',
  `verifydate` datetime DEFAULT NULL,
  `date_created` datetime DEFAULT NULL,
  `date_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username_UNIQUE` (`username`)
)

CREATE TABLE `password_reset` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL,
  `code` varchar(255) NOT NULL,
  `iscompleted` bit(1) DEFAULT b'0',
  `date_created` datetime DEFAULT NULL,
  `date_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uid_UNIQUE` (`uid`)
)
Was it helpful?

Solution

Try this:

DELIMITER $$

CREATE DEFINER=`root`@`%` FUNCTION `password_reset_request`(_spUsername VARCHAR(120)) RETURNS VARCHAR(255) CHARSET utf8
    READS SQL DATA
BEGIN
    DECLARE _vcode VARCHAR(255);
    DECLARE _muid INT(10) DEFAULT 0;
    SET vcode = "test";

    SELECT id INTO _muid 
    FROM scheme.users 
    WHERE username = _spUsername 
    LIMIT 1;

    IF _muid = 0 THEN
        RETURN 'BADUSER';
    ELSE
        INSERT INTO `password_reset`(`uid`,`code`) 
            VALUES ( _muid, _vcode)
        ON DUPLICATE KEY UPDATE
            `code` = _vcode;
        RETURN _vcode;
    END IF;
END$$

DELIMITER ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top