mysqlstored-proceduresphpmyadminsubqueryroutines

How to use a sub query as part of a stored procedure MySQL


I am trying to create a procedure (called a routine in phpMyAdmin) and currently have this query:

BEGIN

INSERT INTO `users` (`username`, `password`, `email`, `user_role_id`,` date_registered`)
    VALUES (_username, _password, _email, (SELECT `ID` FROM `roles` WHERE `role_name` = _role) , _date);

END;

But this does not work, I have tried to declare a variable to a role_ID and this also did not work, can anyone help me to fix this please?

NOTE

The params you see (starting with an underscore (_)) are all IN params used in the phpMyAdmin routine creator

EDIT

The other code I have tried is this:

BEGIN

DECLARE role_id AS/*=*/ (SELECT `ID` FROM `roles` WHERE `role_name` = _role); /* tried both AS and = */

INSERT INTO `users` (`username`, `password`, `email`, `user_role_id`, `date_registered`)
    VALUES (_username, _password, _email, role_id, _date);

END;

Also noticed a small error with the DECLARE, changed the above code to:

BEGIN

DECLARE @role_id ;
SET @role_id = (SELECT `ID` FROM `roles` WHERE `role_name` = _role);

INSERT INTO `users` (`username`, `password`, `email`, `user_role_id`, `date_registered`)
    VALUES (_username, _password, _email, @role_id, _date);

END;

But still no luck


Solution

  • I have worked out how to do this - although not using a subquery, I have this stored procedure:

    BEGIN
    
    INSERT INTO `users` (`username`, `password`, `email`, `user_role_ID`, `date_registered`)
        VALUES (username, pwd, email, role, datenow);
    
    END
    

    and this PHP function and class to work it:

    class create_user
    {
        public static function CreateUser($username, $password, $email, $role)
        {
            global $link;
            #region Get role id
            $role_q = "SELECT `ID` FROM `roles` WHERE `role_name` = '{$role}';";
            $role_rs = mysqli_fetch_row($link->query($role_q));
            $role = $role_rs[0];
            #endregion
    
            #region Create user
            $link->query("CALL sp_create_user('{$username}', '" . hash("sha256", $password) . "', '{$email}', '{$role}', '" . date("y-m-d H:i:s") . "')") ? $inserted = true : $inserted = false;
            #endregion
    
            #region check if user created
            if ($inserted)
            {
                return true;
            }
            else
            {
                return "User was not created. Either the username or email is already in use.";
            }
            #endregion
        }
    }
    

    If someone can do this with a sub query, that will be the correct answer as this works, but is not a full answer for my question.

    Happy SQLing!