-1

I have a profile page which displays user data and users are able to edit their profile information. On the profile page users are able to edit their first name, last name and email. The only field users are not able to update is the Username field as it is displayed as text only and I don't want users to be able to edit their usernames.

Now, everything is displayed and works fine until the user updates their name for example and presses the update button. This reloads the users newly updated information into the fields and at that moment the username field errors out.

The error says:

Notice: Undefined index: username in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\ProjectNet\edit_profile.php on line 128

line 128:

<label>Username: <?php echo $user_info['username'] ?></label>

Below is the rest of the code for the page that receives the error:

<?php


include('init.inc.php');

if (isset($_POST['firstname'], $_POST['lastname'], $_POST['email'])){
    $errors = array();

    if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false){
        $errors[] = 'The email address you entered is not valid.';
    }
    if(preg_match('#^[a-zA-Z ]+$#i', $_POST['firstname']) === 0){
        $errors[] = 'Your first name must only contain a-z characters only.';
    }
    if(preg_match('#^[a-zA-Z ]+$#i', $_POST['lastname']) === 0){
        $errors[] = 'Your last name must only contain a-z characters only.';
    }

    if (empty($errors)){
        set_profile_info($_POST['firstname'], $_POST['lastname'], $_POST['email']);
    }
    $user_info = array(
        'firstname'  => htmlentities($_POST['firstname']),
        'lastname'   => htmlentities($_POST['lastname']),
        'email'      => htmlentities($_POST['email'])
    );
}else{
    $user_info = fetch_user_info($_SESSION['u_id']);
}
?>

<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns=""http://www.w3.org/1999/xhtml>
  <head>
  <title>Edit Your Profile</title>
  <style type="text/css">

    form div {color: white; font-weight: bold; float: left; clear: both; margin: 0px 0px 4px 0px; }
    label {font: 19px/1.5 Arial, Helvetica,sans-serif; color: white; font-weight: bold; float:left; clear:both; margin: 0px 0px 4px 0px; }
    input[type="text"], textarea {font: 16px/1.5 Arial, Helvetica,sans-serif; margin-left: 10px; float:left; width: 400px; }
    input[type="submit"] {
    width: 300px;
    background: #333;
    line-height: 50px;
    color: #e3e3e3;
    border-radius: 6px;
    box-shadow: 0px 0px 2px rgba(0,0,0,.5), 1px 1px 5px rgba(0,0,0,.3);
    cursor: pointer;
    font-weight: bold;
    font: 17px/1.5 Arial, Helvetica,sans-serif;
    float: left;
    position: absolute;
    top: 39%;
    }
    input[type="submit"]:hover {
    background: #e3e3e3;
    color: #333;
    }
  </style>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" href="./css/style.css">
  </head>
  <body>

    <header>
    <nav>
        <div class="main-wrapper">
        <div id="branding">
        <li><h1><span><a href="homepage.php">ProjectNet</a></span></li>
        </div>
        <nav>
          <ul>
            <li><a href="homepage.php">Home</a>
                <ul>
                    <li><a href="findGroup.php">Find A Group</a></li>
                    <li><a href="groupForm.php">Create A Group</a></li>
                </ul>
            </li>
            <li><a href="user_list.php">Members</a></li>

            <li><a href="edit_profile.php">Profile</a></li>
          </ul>

        </nav>

        <!--
            <ul>
                <li><a href="index.php">Home</a></li>
            </ul>
            -->


            <div class="nav-login">
                <?php
                    if (isset($_SESSION['u_id'])) {
                        echo '<form action="includes/logout.inc.php" method="POST">
                              <button type="submit" name="submit">Logout</button>
                              </form>';
                    } else {
                        echo '<form action="includes/login.inc.php" method="POST"> 
                              <input type="text" name="uid" placeholder="Username/Email">
                              <input type="password" name="pwd" placeholder="Password">
                              <button type="submit" name="submit">Login</button>
                              </form>
                              <a href="signup.php">Sign up</a>';
                    }
                ?>
        </div>
    </nav>
        </header>
        <section id="showcase1">



    <div>
        <?php

        if(isset($errors) === false){
            echo 'Click update to edit your profile';
        }else if(empty($errors)) {
            echo 'Your profile has been updated.';
        }else{
            echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
        }

        ?>
    </div>
    <label>Username: <?php echo $user_info['username'] ?></label>
    <form action="" method="post">
        <div>
            <label for="firstname">First name:</label>
            <input type="text" name="firstname" id="firstname" value="<?php echo $user_info['firstname'] ?>" />
        </div>
        <div>
            <label for="lastname">Last name:</label>
            <input type="text" name="lastname" id="lastname" value="<?php echo $user_info['lastname'] ?>" />
        </div>
        <div>
            <label for="email">Email:    </label>
            <input type="text" name="email" id="email" value="<?php echo $user_info['email'] ?>" />
        </div>
        <!--<div>
            <label for="password">Password:</label>
            <input type="text" name="password" id="password" value="" />
        </div> -->
        <div>
            <input type="submit" value="Update" />
        </div>
    </form>
   </section>
      <footer>
        <div class="wrapper">
        <nav>
          <ul>
            <li><a href="about1.php">About</a></li>
            <li><a>&copy; 2018 ProjectNet</a></li>
          </ul>
        </nav>
        </div>
      </footer>
  </body> 
</html>

Backend code:

<?php

// fetches all of the users
function fetch_users(){
    $result = @mysql_query('SELECT `user_id` AS `id`, `user_uid` AS `username` FROM users');

    $users = array();

    while (($row = mysql_fetch_assoc($result)) !== false){
        $users[] = $row;
    }
    return $users;
}

//fetches profile info for the given user
function fetch_user_info($u_id){
    $u_id = (int)$u_id;

    $sql = "SELECT `user_uid` AS `username`, `user_first` AS `firstname`, `user_last` AS `lastname`, `user_email` AS `email` FROM `users` WHERE `user_id` = {$u_id}";

    $result = mysql_query($sql);

    return mysql_fetch_assoc($result);
}

//Updates the current users profile.
function set_profile_info($firstname, $lastname, $email){
    $firstname   = mysql_real_escape_string($firstname);
    $lastname    = mysql_real_escape_string($lastname);
    $email       = mysql_real_escape_string(htmlentities($email));

    $sql = "UPDATE `users` SET `user_first` = '{$firstname}', `user_last` = '{$lastname}', `user_email` = '{$email}' WHERE `user_id` = {$_SESSION['u_id']}";

    mysql_query($sql);
}
?>

Database information: Primary key: user_id username field in the database: user_uid

Qirel
  • 25,449
  • 7
  • 45
  • 62
I Need Help
  • 87
  • 10
  • 1
    **Please**, don't use `mysql_*` functions for new code. They are no longer maintained and the community has begun the [deprecation process](http://news.php.net/php.internals/53799), and `mysql_*` functions have been officially removed in PHP 7. Instead you should learn about [prepared statements](https://en.wikipedia.org/wiki/Prepared_statement) and use either `PDO` or `mysqli_*`. If you can't decide, [this article will help to choose your best option](http://php.net/manual/en/mysqlinfo.api.choosing.php). – GrumpyCrouton Apr 10 '18 at 20:59
  • 1
    [Little Bobby](http://bobby-tables.com/) says **[you may be at risk for SQL Injection Attacks](https://stackoverflow.com/q/60174/)**. Learn about [Prepared Statements](https://en.wikipedia.org/wiki/Prepared_statement) with [parameterized queries](https://stackoverflow.com/a/4712113/5827005). I recommend `PDO`, which I [wrote a class for](https://github.com/GrumpyCrouton/GrumpyPDO) to make it extremely easy, clean, and more secure than using non-parameterized queries. Also, [This article](https://phpdelusions.net/pdo/mysqli_comparison) may help you choose between `MySQLi` and `PDO` – GrumpyCrouton Apr 10 '18 at 20:59
  • You should look into separating parts of your code, this is quite messy. And not to mention, you're using **old and insecure libraries**! Drop the MySQL extension and learn PDO or MYSQLi with prepared statements instead. – Qirel Apr 10 '18 at 21:03
  • Poor handling of errors as well, you're suppressing them with `@` instead of handling them as you should be doing. – Qirel Apr 10 '18 at 21:03
  • This is just a project I'm working on locally so security is not an issue. I've been following suite with a load of tutorials which use the old php functions. Depreciated code for me is not the main issue, the main issue which I mainly asked help for is the error I am getting.... – I Need Help Apr 10 '18 at 21:17
  • 1
    Seems you build the '$user_info' array. But, it appears you never add 'username' to the array. That's why you get that error. – CharlesEF Apr 10 '18 at 21:19
  • @CharlesEF Thank you, I've tried to add it in and made a mess of it (I'm a beginner). All the data on the profile page shifted up so the last name field data is now in the first name field, etc. would you be able to help me out with the way to layout the code? Help is much appreciated. – I Need Help Apr 10 '18 at 21:32
  • 1
    If you want 'username' to be sent with the other data then you have to add a field in the form with the name 'username'. That field can be hidden (type="hidden"). Because the data is coming from a database there is no problem as far as data moving up or down. If you want to access '$_POST['username']' then you must add a hidden field to the form. – CharlesEF Apr 10 '18 at 22:01
  • @CharlesEF Thank you for the help, in the form I set the field for username as you stated but am still getting an error (undefined index: username), Would you be able to possibly write how it would be within my code? This is what I done: – I Need Help Apr 10 '18 at 22:22

1 Answers1

1

Ok, my suggestion is based on how you build the '$user_info' array. Your form should look like this:

<form>
  <input type="hidden" name="username" value="<?php echo $user_info['username'] ?>">
  the rest of your labels, inputs and submit button go here
</form>

Then you need to modify this code:

$user_info = array(
    'username'  => htmlentities($_POST['username']),
    'firstname'  => htmlentities($_POST['firstname']),
    'lastname'   => htmlentities($_POST['lastname']),
    'email'      => htmlentities($_POST['email'])
);

Hope this helps. Post back if you need more help. Also as your next learning step look in to 'isset' so you can test the variable before you use it.

CharlesEF
  • 608
  • 1
  • 15
  • 25
  • Thank you for the continuous help, really appreciate it dude. All is good now, I had to take the hidden field out though to be able to view the username field. Also, because the input tag to display the username, a white box appears behind the username data field, do you know away to get rid of the white box for the input tag on the web page? If not, that's fine, thanks again for your help :) – I Need Help Apr 11 '18 at 14:05
  • You can show the username just as you had before. Adding a hidden input field will not change that. Remember, when you submit a form all fields/controls in the form are sent to the server as name/value pairs. As for your white box problem, it could be nothing more than a background color for the input. To be sure I need to see the HTML where the username goes. – CharlesEF Apr 11 '18 at 15:25