19 Replies Latest reply on Apr 28, 2010 10:57 AM by F.Bowman

    Retrieving a userid variable for a logged in user

    jimmyoneshot Level 1

      My app displays items dynamically based on the value of a variable userid i.e. if userid is 1 all of the items in my array collection that have the userid of 1 will be displayed in a tilelist.

       

      What I want to do is have a log in system which will log users in but will also get the userid for that specific user and set it as my userid variable in my app so the app knows what user is logged in and can display any information relevant to that user.

       

      My mysql table that stores all the users has the columns userid (the value I want which is specific to each user) username and password.

       

      I've been using this tutorial which lets the user log in and if the login is successful some type of message is displayed but this solution doesn't allow the app to store what user is logged in via userid:-

       

      http://cookbooks.adobe.com/post_Create_a_login_system_with_Flex_and_PHP-7243.html

       

      Can anyone give me any advice on how to do this or what I'd need to do to modify this example to get the userid for the logged in user into my userid variable in my app please or recommend something similar?

        • 1. Re: Retrieving a userid variable for a logged in user
          F.Bowman Level 2

          This is what I would do.

           

          In your login system, when the user authenticates successfully, send back XML data from the backend that includes the user's id as it is in the database.

           

          See that part of the tutorial where it says "//start outputting the XML" ?? That section is where you'd add in the additional data to send back to your Flex application.

           

          The query example they used is ideal since it fetches the entire row from the database. You just need to fetch the particular columns from the result and add them to the XML to send back to your Flex app.

          1 person found this helpful
          • 2. Re: Retrieving a userid variable for a logged in user
            jimmyoneshot Level 1

            Hi cheers F.Bowman. That is similar to the way I'd do it and in fact since I've asked my last question I've edited the last output part ($param_username is the username that has just been passed from flex) to this:-

             

            $userid = "SELECT userid FROM users WHERE username='$param_newusername'";

            $output = "<checklogin>";
            if(!$result){
              $output .= "no"; 
            }else{
              $output .= "$userid";
            }
            $output .= "</checklogin>";

            print ($output);

             

            And changed my flex code to this so that if it outputs nothing the username will be invalid but if it outputs a userid the login will be valid and the user will be logged in.

             

             

             

            if(evt.result.checklogin !== "")

            {

             

            //loginWindow.visible=false;

            loginstatus.text=

             

            "Logged In";

            }

             

            if(evt.result.checklogin == "")

            {

            loginstatus.text=

            "Invalid Username/Password";

            }

             

            Does this seem right to you?

             

            Also I'm struggling to work out how I can assign 1 single number (userid) into my variable via that same result handler. I've saved whole xml documents as array collections but how would I exactly save 1 number from xml to a variable (userid) in my app?

            • 3. Re: Retrieving a userid variable for a logged in user
              F.Bowman Level 2

              Let me write up some code and post it up for you.

              1 person found this helpful
              • 5. Re: Retrieving a userid variable for a logged in user
                F.Bowman Level 2

                This is the PHP code. Let me know if you need Flex code as well. I tried to comment it as much as possible. Let me know if you need clarification on any piece.

                 

                <?php
                
                //Capture credentials from POST data.
                $username = $_POST['username'];
                $password = $_POST['password'];
                
                //Initiate connection to the database.
                if(!$dbConnection = mysqli_connect($host, $username, $password, $database)
                {
                     exit('Could not connect to the database for some reason.');
                }
                
                //Credential verification query.
                $dbQuery = "SELECT * FROM users WHERE username='$username' AND password='$password'";
                
                //Perform the query and save the results.
                $queryResult = mysqli_query($dbConnection, $dbQuery);
                
                //Verify whether a user was found.
                if(mysql_num_rows($queryResult) == 1)
                {
                     $queryData = mysqli_fetch_assoc($queryResult);
                     $userID = $queryData['user_id'];
                     
                     xmlOutput("You've logged in successfully", "$userID", "login");
                }
                else
                {
                     xmlOutput('The username and password you entered were incorrect', '', 'login');
                }
                
                
                //Function for outputting results in XML.
                //Message - A status or informational message.
                //Data - Data from a successful query.
                //Function - the Function that was called.
                function xmlOutput($message=null, $data=null, $function=null)
                {
                     header('Content-type: application/xml; charset="utf8"');
                     
                     $xmlOutput = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xmlOutput .= "<transmission>\n";
                     $xmlOutput .= "<message>$message</message>\n";
                     $xmlOutput .= "<data>$data</data>\n";
                     $xmlOutput .= "<function>$function</function>\n";
                     $xmlOutput .= "</transmission>\n";
                     
                     echo $xmlOutput;
                }
                
                ?>
                

                 

                 

                Sorry about the delay before the response. I had to go attend a workshop.

                • 6. Re: Retrieving a userid variable for a logged in user
                  jimmyoneshot Level 1

                  No worries mate that's brilliant. Thanks so much for taking the time to help me. My biggest problem though will indeed be handling this data in flex, more specifically assigning the userid value produced in that xml to my userid variable that I have in my Flex app. I think I'd do this in a result handler but as I say I'm not sure on how exactly.

                   

                  Plus I'm not sure on how that php file will output the userid value as xml too. Will I need to replace $data with $userid in the output part or something as it's mainly the userid that I want?

                   

                  Sorry I'm clueless at php and only know the basics and everytime I try to ask a question on phpforums they seem to just ignore me or laugh me off

                   

                  All I really need it to do in Flex is if the user logs in incorrectly to just change the text of a label I have to "Ircorrect login" or something like that and if they login succesfully to display a successful message instead and assign the userid value from the xml to my userid variable in my application.

                  • 7. Re: Retrieving a userid variable for a logged in user
                    jimmyoneshot Level 1

                    I've modified the code you gave me to the following except I also changed user_id to userid as that's what the column is called in my table, but I'm still struggling to output the userid in flex:-

                     

                     

                     

                    <?php
                    header("Content-type: text/xml"); 
                    $host = "";
                    $username = "";
                    $password = "";
                    $db_name = "";
                    $mysql_connection = mysql_connect($host, $username, $password);
                    mysql_select_db($db_name);
                    $param_requesttype = $_POST["requesttype"];
                    $param_username = $_POST["username"];
                    $param_password = $_POST["password"];
                    $query = "SELECT * FROM users WHERE username = '$param_username' AND password = '$param_password'";
                     
                    $result = mysql_fetch_array(mysql_query($query));
                    if(mysql_num_rows($result) == 1)
                    {
                         $queryData = mysqli_fetch_assoc($result);
                         $userid = $queryData['userid'];
                         
                         xmlOutput("You've logged in successfully", "$userid", "login");
                    }
                    else
                    {
                         xmlOutput('The username and password you entered were incorrect', '', 'login');
                    }
                    
                    //Function for outputting results in XML.
                    //Message - A status or informational message.
                    //Data - Data from a successful query.
                    //Function - the Function that was called.
                    function xmlOutput($message=null, $data=null, $function=null)
                    {
                         header('Content-type: application/xml; charset="utf8"');
                         
                         $xmlOutput = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                         $xmlOutput .= "<transmission>\n";
                         $xmlOutput .= "<message>$message</message>\n";
                         $xmlOutput .= "<data>$data</data>\n";
                         $xmlOutput .= "<function>$function</function>\n";
                         $xmlOutput .= "</transmission>\n";
                         
                         echo $xmlOutput;
                    }
                    ?>
                    
                    
                    • 8. Re: Retrieving a userid variable for a logged in user
                      F.Bowman Level 2

                      Ok. I'll write up some more code but for Flex for handling the data that is sent.

                      • 9. Re: Retrieving a userid variable for a logged in user
                        jimmyoneshot Level 1

                        Thanks again mate. You're a saint. Whenever you have the time.

                        • 10. Re: Retrieving a userid variable for a logged in user
                          F.Bowman Level 2

                          When I'm done, we'll be able to get the user id into Flex.

                           

                          What you said is correct, we'll be using the result handler to retrieve the data. The way we'll be using the result handler is to hand off to specific functions based on the response we get from sending requests to the php file.

                           

                          If you noticed the last parameter that my xmlOutput() function in the php file takes, that allows us to specify which function in the php file was requested so that we hand back off to the correct function when the result comes back. I hope that's not too confusing.

                          • 11. Re: Retrieving a userid variable for a logged in user
                            jimmyoneshot Level 1

                            I think I understand. The only part I didn't really get was the $message $data etc bits as I'm assuming they are inbuilt functions of php or something. But as long as I can somehow get that variable for the logged in user and set it as my userid variable in the app I'm happy I tweaked your code a little bit to this but it still seems to operate the same. It's just that the numrows part confuses me in php and using (!result) is similar to flex code which is what I'm used to:-

                             

                             

                            <?php
                            header("Content-type: text/xml"); 
                            $host = "localhost";
                            $username = "coolvisi";
                            $password = "joanne";
                            $db_name = "coolvisi_interface";
                            $mysql_connection = mysql_connect($host, $username, $password);
                            mysql_select_db($db_name);
                            $param_requesttype = $_POST["requesttype"];
                            $param_username = $_POST["username"];
                            $param_password = $_POST["password"];
                            $query = "SELECT * FROM users WHERE username = '$param_username' AND password = '$param_password'";
                             
                            $result = mysql_fetch_array(mysql_query($query));
                            if(!$result)
                            {
                                 xmlOutput('The username and password you entered were incorrect', '', 'login');
                            }
                            else
                            {
                                 $queryData = mysqli_fetch_assoc($result);
                                 $userid = $queryData['userid'];
                                 
                                 xmlOutput("$userid", "$userid", "login");
                            }
                            
                            //Function for outputting results in XML.
                            //Message - A status or informational message.
                            //Data - Data from a successful query.
                            //Function - the Function that was called.
                            function xmlOutput($message=null, $data=null, $function=null)
                            {
                                 header('Content-type: application/xml; charset="utf8"');
                                 
                                 $xmlOutput = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                                 $xmlOutput .= "<transmission>\n";
                                 $xmlOutput .= "<message>$message</message>\n";
                                 $xmlOutput .= "<data>$data</data>\n";
                                 $xmlOutput .= "<function>$function</function>\n";
                                 $xmlOutput .= "</transmission>\n";
                                 
                                 echo $xmlOutput;
                            }
                            ?>
                            
                            
                            • 12. Re: Retrieving a userid variable for a logged in user
                              F.Bowman Level 2

                              Ah. The mysql_num_rows function tests the result of the query to see how many rows were returned. Naturally, there should only be one row returned when you perform a query that relates to authentication. If a row is returned for the username and password combination, the php app proceeds to retrieve the user id for that person and send it on it's merry way to the Flex app.

                              • 13. Re: Retrieving a userid variable for a logged in user
                                F.Bowman Level 2

                                Alright. Here's some Flex code.

                                 

                                /*
                                 *
                                 * Actionscript
                                 *
                                 */
                                
                                private function handlerRequestFault(event:FaultEvent):void
                                {
                                     //Fault code goes here.
                                }
                                
                                private function handlerRequestResult(event:ResultEvent):void
                                {
                                     handlerServerResponse(event.result);
                                }
                                
                                private function handlerServerResponse(response:object):void
                                {
                                     var xmlData:XML = new XML(response);
                                
                                     xmlData.elements("data") should now be equal to your user id. I think there's
                                     supposed to be a different way to reference it but this works for now.
                                }
                                
                                
                                /*
                                 *
                                 * MXML
                                 *
                                 */
                                
                                <mx:HTTPService
                                     id="loginRequest"
                                     url="http://url.to.php.app"
                                     method="POST"
                                     resultFormat="text"
                                     result="handlerRequestResult(event);"
                                     fault="handlerRequestFault(event);"
                                     showBusyCursor="true"
                                     >
                                     <mx:request xmlns="">
                                          <username>{username.text}</username>
                                          <password>{password.text}</password>
                                     </mx:request>
                                </mx:HTTPService>
                                

                                 

                                Let me know if you need any clarification for any of it.

                                • 14. Re: Retrieving a userid variable for a logged in user
                                  jimmyoneshot Level 1

                                  Thanks again Bowman. So in the fault result part in the actionscript will be what message to show if the user enters an incorrect username/password?

                                   

                                  The thing I still haven't got a clue on is how to assign the userid which you say is now in the data to my userid variable but it's just because I really don't understand the code that you used. You see I need to use the userid variable to filter certain things etc based on what user has logged in so I need to be able to do things with that userid variable and make it bindable etc as I like to bind these variables to the text property of labels while I'm testing the code so it will display them and I know I['ve actually got the correct variable and it's all working right etc.

                                   

                                  Thanks for your help, you've been brilliant, it's just my own lack of knowledge that's holding me back

                                  • 15. Re: Retrieving a userid variable for a logged in user
                                    F.Bowman Level 2

                                    You're welcome. I'll keep replying once I can until you have it down and working.

                                     

                                    The result part of the HTTPService is for if the Flex application encounters difficulties when trying to communicate with the php app. So if it doesn't find it or there is some other error, that's when the fault comes into play.

                                     

                                    All responses from the php app comes in the request result.

                                     

                                    Once the request is sent out, we should have had a response back from the server with the user id of the user being sent back to the Flex app. It's up to you to assign it to a variable or whatever else.

                                     

                                    Should I just write up a working system instead of doing code snippets so you see how I'm getting it done? I could post the files up once I do that.

                                    • 16. Re: Retrieving a userid variable for a logged in user
                                      jimmyoneshot Level 1

                                      Theres no need to do that mate. It seems to be pretty much working as it is. The only bit I'm confused about is what to put into the fault handler brackets. Basically I have a label in my app called loginstatus. If the user logs in incorrectly the text of that label should change to something that says that eg "Incorrect login" or something and if they log in correctly it should display "logged in correctly" or something and obviously we should then get the userid value.

                                       

                                       

                                      That's the problem I don't know the code to get the userid from the data into my variable. That may sound silly but it's just something I haven't done before but I need to get that data for the app to function.

                                       

                                      I tried putting this in the result handler, something like:-

                                       

                                      userid=event.result.blah.blah etc

                                       

                                      But that doesn't seem to work.

                                      • 17. Re: Retrieving a userid variable for a logged in user
                                        F.Bowman Level 2

                                        If you did the Flex code the way I did it, the following should work:-

                                         

                                        //Assuming that you have a variable defined called userid.
                                        
                                        private function handlerServerResponse(response:object):void
                                        {
                                             var xmlData:XML = new XML(response);
                                        
                                             userid = xmlData.elements("data");
                                        }
                                        
                                        Keep these two functions in tact as well.
                                        
                                        //This function handles errors when trying to communicate with the php script.
                                        private function handleRequestFault(event:FaultEvent):void
                                        {
                                             trace("There was an error communicating with the script.");
                                             trace(event);
                                        }
                                        
                                        //This function handles all successful responses from the php script.
                                        private function handlerRequestResult(event:ResultEvent):void
                                        {
                                             //Passes the result of the http request to the processing function.
                                             handlerServerResponse(event.result);
                                        }
                                        

                                        • 18. Re: Retrieving a userid variable for a logged in user
                                          jimmyoneshot Level 1

                                          Thanks so much for all your help mate. I'm sure I'll be fine now. I'm trying another way to get other results from another request I have into a variable but I'll save that for another topic. You've been brilliant. All the best.

                                          • 19. Re: Retrieving a userid variable for a logged in user
                                            F.Bowman Level 2

                                            Glad I could be of help. Have a great one.