Hi, I'm using PHP, I am trying to develop:
1. a login page in HTML, once user enter the correct username and password, this will be directed to the User page.
2. In User page, there will be some text fields of the user (eg. name and address), all these suppose to retrieve from SQL Server. In here, if the username is found in the database, his/her data will be displayed in the textboxes ( eg. name and address), if not, the textboxes remain empty. User can choose to edit or enter new data into the textboxes and submit back to the datadase.
3. Once updated, user can click "save and logout" to save the data and logout.
I've done the login part, but only in (2), I can't retrieve the user's data from databases based on User.Identity.Name. Any idea how to retrieve data based on user's username?
Thanks.

Do you have any code started? If you have the login process done then in my opinion you've done the hardest part. Just write a simple SQL query to Select data from your table Where the username submitted is equal to the username column in your table. If it is found then you can fetch any information about that record and display it to the page, if not then they shouldn't have been logged in from the way I believe you have your code. To insert data it's the same concept just update the table where the username is equal to the username in the table and only update the fields you are displaying.

Member Avatar for diafol

I'd just add, that you only need to keep the user id in a session, unless you want to have soething like logout username. Searching on the primary key should be quicker than the actual username itself.

Yes, I agree with diafol. When selecting user data based on the condition of the username (i.e. WHERE username = ?), provided the username is not a unique field you can have multiple rows returned. So is always advisable that at the login page, after a successful login, a user id is stored as a session. Thus retrieving user info will be just a simple sql statement with id being used as the filter.

But If you can show your codes. (About the retrieving) And we can help.

Good luck

Is this you want? (3 user level login for the code below)

if ($_POST['doLogin']=='Login'){            //When click login 
    foreach($_POST as $key => $value) {
        $data[$key] = filter($value);       // post variables are filtered
    }

    $user_email = $data['usr_email'];
    $pass = $data['pwd'];

    if (strpos($user_email,'@') == false) {
        $user_cond = "user_name='$user_email'";
    }

    else {
        $user_cond = "user_email='$user_email'";
    }

    $result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE $user_cond AND `banned` = '0'") or die (mysql_error()); 
    $num = mysql_num_rows($result);

  // Match row found with more than 1 results  - the user is authenticated. 
    if ( $num > 0 ) { 
        define ("ADMIN_LEVEL", 5);
        define ("USER_LEVEL", 1);
        define ("GUEST_LEVEL", 0);

        list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);

        if($_SESSION['user_level'] == ADMIN_LEVEL) {
            header("Location: adminPanel/adminHome.php");     //redirect page
        }

        if($user_level == 1){
            header("Location: home.php");
        }

        if(!$approved) {
            //$msg = urlencode("Account not activated. Please check your email for activation code");
            $err[] = "Account not activated. Please check your email for activation code";
            // header("Location: home.php?msg=$msg");
            // exit();
        }

        //check against salt
        if ($pwd === PwdHash($pass,substr($pwd,0,9))) { 
            if(empty($err)){            
             // this sets session and logs user in  
               session_start();
               session_regenerate_id (true); //prevent against session fixation attacks.

               // this sets variables in the session 
                $_SESSION['user_id']= $id;  
                $_SESSION['user_name'] = $full_name;
                $_SESSION['user_level'] = $user_level;
                $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);

                //update the timestamp and key for cookie
                $stamp = time();
                $ckey = GenKey();
                mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());

                //set a cookie 
                if(isset($_POST['remember'])){
                      setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
                      setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
                      setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
                } 

                header("Location: home.php");
            }
        }

        else{
            $msg = urlencode("* Invalid Login. Please try again with correct username/email and password.");
            header("Location: homeshow.php?msg=$msg");
        }
    }
Member Avatar for diafol

With respect Lau, that isn't a script you should use these days. mysql functions have been deprecated. Also filter() seems to be a udf that isn't shown.

opps, sorry, what should make change to the script?

Member Avatar for diafol

Well, use mysqli or PDO for your DB retrieval/manipulation. As far as it goes, it's not actually that bad a script. Where did you get it?

Missing UDFs:

filter()
GenKey()

Make by own, used previously. Thanks for your advice ya :)

Member Avatar for diafol

Ok, my mistake. How about including the filter and GenKey functions for completeness? As a rule, we try not to provide code without seeing what the OP has done first, otherwise the site attracts leeches. We try(!) to hep people to code for themselves. However, the horse has already bolted here, so providing the 2 functions may shine further light on the script you provided.

Just for reference,

For function GenKey()

function GenKey($length = 7){
    $password = "";
    $possible = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 

    $i = 0; 

    while ($i < $length) { 
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

    if (!strstr($password, $char)) { 
        $password .= $char;
        $i++;
    }
  }

  return $password;
}

For function filter(),

function filter($data) {
    $data = trim(htmlentities(strip_tags($data)));

    if (get_data())
        $data = stripslashes($data);

    $data = mysql_real_escape_string($data);

    return $data;
}

if any mistake or out-of-date, just tell me !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.