SitePoint Sponsor

User Tag List

Results 1 to 19 of 19

Thread: Add Else Option

  1. #1
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Add Else Option

    Hi,

    Im trying to add an else option to a page to show that someone is not logged in.


    Code:
    			<?php
    $query = mysql_query("SELECT * FROM users ORDER BY ID DESC LIMIT 1");
    while($row = mysql_fetch_array($query)) {
    
    	
    	 if($query){
    '<li>You are sucessfully logged in as <?php echo $row['id']; ?>.</li>' }
    else($query){
    '<li>You are currently not logged in.</li>'
    	
    
    }
    }
    ?>

    The following code works fine but Im trying to add the above else option. Can anyone please advise how I can make the else work.


    Code:
    			<?php
    $query = mysql_query("SELECT * FROM users ORDER BY ID DESC LIMIT 1");
    while($row = mysql_fetch_array($query)){
        ?> 
    
    <li>You are sucessfully logged in as <?php echo $row['id']; ?>.</li> 
    
    <?php
    }
    ?>

  2. #2
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,234
    Mentioned
    154 Post(s)
    Tagged
    0 Thread(s)
    First of all, when expecting a single row, ditch the while loop, it is unnecessary.

    Which then gives you the following:
    PHP Code:
    <?php
    $query 
    mysql_query("SELECT * FROM users ORDER BY ID DESC LIMIT 1");
    if (
    $query && mysql_num_rows($query) === 1// query was successful and returned 1 row
    {
      
    $row mysql_fetch_array($query);
      echo 
    '<li>You are sucessfully logged in as ' $row['id'] . '</li>';
    } else {
      echo 
    '<li>You are currently not logged in.</li>';
    }
    ?>

  3. #3
    SitePoint Addict kduv's Avatar
    Join Date
    May 2012
    Location
    Atlanta, GA
    Posts
    244
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    And looking at your SQL, it looks like as long as there are any records in your DB at all, every user will be seen as "logged in".

  4. #4
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,234
    Mentioned
    154 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kduv View Post
    And looking at your SQL, it looks like as long as there are any records in your DB at all, every user will be seen as "logged in".
    Okay, today is showing I didn't get a lot of sleep over the past couple of nights, yet another obvious piece I missed. Very good catch @kduv ;

  5. #5
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kduv View Post
    And looking at your SQL, it looks like as long as there are any records in your DB at all, every user will be seen as "logged in".
    Hi, what does this mean sorry? It something I should be concerned about?



    The code you code you provided works fine however it displays the id twice.

    I am trying to replace the following "You are currently not logged in." with the following code but this creates an error. How do I add divs into an area like this please?

    Code:
    			<div class="headerlinkright">
    		<a href="/siteinfo/aboutus.php"   rel="nofollow" class='bloglink'   >About Us</a>
    </div>
    						<div class="headerlinkright">
    <a href="/blog/blog.php"   rel="nofollow" class='bloglink'   >Blog</a>
    </div>
    
    						</div>

  6. #6
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,234
    Mentioned
    154 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by justlukeyou View Post
    Hi, what does this mean sorry? It something I should be concerned about?
    If you look at your SQL query, "SELECT * FROM users ORDER BY ID DESC LIMIT 1" you are not limiting it with a WHERE clause to check that the User is truly logged in, you are simply checking that at least 1 user exists in the table.



    Quote Originally Posted by justlukeyou View Post
    The code you code you provided works fine however it displays the id twice.

    I am trying to replace the following "You are currently not logged in." with the following code but this creates an error. How do I add divs into an area like this please?

    Code:
                <div class="headerlinkright">
            <a href="/siteinfo/aboutus.php"   rel="nofollow" class='bloglink'   >About Us</a>
    </div>
                            <div class="headerlinkright">
    <a href="/blog/blog.php"   rel="nofollow" class='bloglink'   >Blog</a>
    </div>
    
                            </div>
    Can you paste your entire code so I can see it as a whole? It is hard to figure things out only seeing segments at a time.

  7. #7
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    Should I be using this?


    Code:
     <?php
         $query = 'SELECT * FROM users WHERE id = "' . mysql_real_escape_string($id) . '" LIMIT 1';  
    if ($query && mysql_num_rows($query) === 1) // query was successful and returned 1 row
    {
      $row = mysql_fetch_array($query);
      echo '<li>You are sucessfully logged in as ' . $row['id'] . '</li>';
    } else {
      echo '<a href="/blog/blog.php"     >Blog</a>';
    }
    ?>

  8. #8
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Damn no its not this because when I create two profiles and login with the first it gives me the ID number of the second profile!

  9. #9
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    This is all the code. The is that someone logs in and then goes the index page which displays their unique ID number (I will change this profile name)

    Login Page

    Code:
        // Reset errors and success messages  
        $errors = array();  
        $success = array();  
        // Login attempt  
        if(isset($_POST['loginSubmit']) && $_POST['loginSubmit'] == 'true'){  
            $loginEmail = trim($_POST['email']);  
            $loginPassword  = trim($_POST['password']);  
              
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
      $error = 'Please enter your email address in a valid format.  Example: bobsmith@companyname.com';
    } 
              
            if(strlen($loginPassword) < 6 || strlen($loginPassword) > 12)  
                $errors['loginPassword'] = 'Your password must be between 6-12 characters.';  
              
            if(!$errors){  
                $query  = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($loginEmail) . '" AND password = MD5("' . $loginPassword . '") LIMIT 1';  
                $result = mysql_query($query);  
                if(mysql_num_rows($result) == 1){  
                    $user = mysql_fetch_assoc($result);  
                    $query = 'UPDATE users SET session_id = "' . session_id() . '" WHERE id = ' . $user['id'] . ' LIMIT 1';  
                    mysql_query($query);  
                    header('Location: index.php');  
                    exit;  
                }else{  
                    $errors['login'] = 'No user was found with the details provided.';  
                }  
            }  
        }  
          
        // Register attempt  
        if(isset($_POST['registerSubmit']) && $_POST['registerSubmit'] == 'true'){  
            $registerEmail = trim($_POST['email']);  
            $registerPassword = trim($_POST['password']);  
            $registerConfirmPassword    = trim($_POST['confirmPassword']);  
                        
            if(strlen($registerPassword) < 6 || strlen($registerPassword) > 12)     
                $errors['registerPassword'] = 'Your password must be between 6-12 characters.';  
              
    		      if($password != $confirmPassword && !$error) {
            $error = "The passwords you entered did not match.";
        }
    	
    $emailAddress = filter_var($_POST['emailaddress'], FILTER_VALIDATE_EMAIL);
    if (!$emailAddress)
    {
      $error = 'Please enter your email address in a valid format.  Example: bobsmith@companyname.com';
    } 
    	
            if($registerPassword != $registerConfirmPassword)  
                $errors['registerConfirmPassword'] = 'Your passwords did not match.';  
              
            // Check to see if we have a user registered with this email address already  
            $query = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($registerEmail) . '" LIMIT 1';  
            $result = mysql_query($query);  
            if(mysql_num_rows($result) == 1)   
                $errors['registerEmail'] = 'This email address already exists.';  
              
            if(!$errors){  
                $query = 'INSERT INTO users SET email = "' . mysql_real_escape_string($registerEmail) . '",  
                                                                                password = MD5("' . mysql_real_escape_string($registerPassword) . '"),  
                                                                                date_registered = "' . date('Y-m-d H:i:s') . '"';  
                  
                if(mysql_query($query)){  
                    $success['register'] = 'Thank you for registering. You can now log in on the left.';  
                }else{  
                    $errors['register'] = 'There was a problem registering you. Please check your details and try again.';  
    				
    			         }  
            }  
              	
    			}	
    				
    				
    				
    
    	
        $query = mysql_query("SELECT id FROM users WHERE email = '".$email."' LIMIT 1");
        if(mysql_num_rows($query) > 0 && !$error) {
            $error = "Sorry, that email is already in use!";
        }
    	 
         print_r($website);  
    	
        if(!$error) {
            $query = mysql_query("INSERT INTO users (email) VALUES ('".$password."', '".$password."', '".mysql_real_escape_string(md5($password))."', '".$email."')");
            if($query) {
                $message = "Hello ".$_POST['email'].",\r\n\r\nThanks for registering with EventVital.com! We hope you enjoy your stay.\r\n\r\n Many Thanks,\r\n.com";
                $headers = "From: ".$website['name']." <".$website['email'].">\r\n";
                mail($_POST['email'], "Welcome", $message, $headers);
                setcookie("user", mysql_insert_id(), $time);
                setcookie("pass", mysql_real_escape_string(md5($password)), $time);
                header("Location: users.php");
            } else {
                $error = "There was a problem with the registration. Please try again.";
            }
        }
    
    			
    			echo $_POST['email'];
    echo $message;
    echo $headers;			
    
        
        ?>
    Index

    Code:
     <?php
         $query = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($email) . '" LIMIT 1';  
    if ($query && mysql_num_rows($query) === 1) // query was successful and returned 1 row
    {
      $row = mysql_fetch_array($query);
      echo '<li>You are sucessfully logged in as ' . $row['id'] . '</li>';
    } else {
      echo '<a href="/blog/blog.php"     >Blog</a>';
    }
    ?>

  10. #10
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Im trying to read it by the email address in the database to show the corresponding ID number. Can anyone advise how I can do this please?

  11. #11
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,234
    Mentioned
    154 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by justlukeyou View Post
    Im trying to read it by the email address in the database to show the corresponding ID number. Can anyone advise how I can do this please?
    It is on my to do list. I might not be able to get to it tonight, but I should be able to get to it tomorrow.

  12. #12
    SitePoint Addict kduv's Avatar
    Join Date
    May 2012
    Location
    Atlanta, GA
    Posts
    244
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    Try something like this ...

    Login Page:
    PHP Code:
    <?php
        session_start
    ();
        
    $_SESSION['userLoggedIn'] = 0;
        
    $_SESSION['userEmail'] = '';
        
    $_SESSION['userID'] = '';
        
        
    // Reset errors and success messages
        
    $errors = array();
        
    $success = array();
        
        
    // Login attempt
        
    if(isset($_POST['loginSubmit']) && $_POST['loginSubmit'] == 'true')
        {
            
    $loginEmail filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
            
    $loginPassword    trim($_POST['password']);

            if (
    $loginEmail === false)
            {
              
    $errors['loginEmail'] = 'Please enter your email address in a valid format.    Example: bobsmith@companyname.com';
            }

            if(
    strlen($loginPassword) < || strlen($loginPassword) > 12)
            {
                
    $errors['loginPassword'] = 'Your password must be between 6-12 characters.';
            }

            if(
    count($errors) === 0)
            {
                
    $query    'SELECT * FROM users WHERE email = "' mysql_real_escape_string($loginEmail) . '" AND password = MD5("' $loginPassword '") LIMIT 1';
                
    $result mysql_query($query);
                if (!
    $result)
                {
                    die(
    'Invalid query: ' mysql_error());
                }
                
                if(
    mysql_num_rows($result) === 1)
                {
                    
    $row mysql_fetch_assoc($result);
                    
    $_SESSION['userLoggedIn'] = 1;
                    
    $_SESSION['userEmail'] = $loginEmail;
                    
    $_SESSION['userID'] = $row['id'];
                    
                    
    header('Location: index.php');
                    exit;
                } else {
                    
    $errors['login'] = 'No user was found with the details provided.';
                }
            }
        }
        
    /*
          The rest of your login page code
        */
    And your index page:
    PHP Code:
    <?php
        session_start
    ()
        
        if (
    $_SESSION['userLoggedIn'])
        {
          echo 
    '<li>You are sucessfully logged in as ' $_SESSION['userEmail'] . ' (ID: '$_SESSION['userID'] . ')</li>';
        } else {
          echo 
    '<a href="/blog/blog.php"     >Blog</a>';
        }
    ?>
    Last edited by kduv; Sep 19, 2012 at 18:38. Reason: Typo

  13. #13
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,234
    Mentioned
    154 Post(s)
    Tagged
    0 Thread(s)
    Thanks @kduv ; for developing this further.

    The only thing I would change, is to use mysql_real_escape_string() around $loginPassword too. Since it is being concatenated into the query, it is still susceptible to a SQL Injection attack.

    Updated line:
    PHP Code:
    $query    'SELECT * FROM users WHERE email = "' mysql_real_escape_string($loginEmail) . '" AND password = MD5("' mysql_real_escape_string($loginPassword) . '") LIMIT 1'

  14. #14
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    This works brilliantly, one thing puzzles me though. When I delete the profile from the database and the refresh the index page it still shows as logged in.

    Is it okay to do this?

  15. #15
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,234
    Mentioned
    154 Post(s)
    Tagged
    0 Thread(s)
    With the way it is coded, it will do that up until the session expires. You can call session_stop() to kill the session when the user is deleted (if doing it programmatically). Or you can verify the session data on each page load by querying against your users table to verify the $_SESSION['userEmail'] the $_SESSION['userID'] are valid.

  16. #16
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Sounds complicated! Im trying to think of every eventuality as Im completely new to registration scripts.

    I'm trying to use this on the logout page but it no longer works. Should I be using this as the session

    Code:
    ($_SESSION['userLoggedIn'])
    Code:
      $query = 'UPDATE users SET session_id = NULL WHERE id = ' . $_SESSION['user']['id'] . ' LIMIT 1';  
        mysql_query($query);  
        unset($_SESSION['user']);  
        header('Location: displaytest.php');  
        exit;

  17. #17
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,234
    Mentioned
    154 Post(s)
    Tagged
    0 Thread(s)
    You will need to use unset on all session variables
    PHP Code:
    unset($_SESSION['userLoggedIn']);
    unset(
    $_SESSION['userEmail']);
    unset(
    $_SESSION['userID']) 
    Your session_id column in the users table is never updated on login, so I don't think setting that to null will do anything

  18. #18
    SitePoint Guru
    Join Date
    Feb 2007
    Posts
    731
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    That worked a treat.

    You guys are bloody good at this.

  19. #19
    SitePoint Addict kduv's Avatar
    Join Date
    May 2012
    Location
    Atlanta, GA
    Posts
    244
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    You can also simply do:
    PHP Code:
    $_SESSION ''
    It really all comes down to how you want to do it. There is no "one correct way".


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •