UPDATE UNIQUE USERS

Hi guys. I am working on an update function which edits users of the admin area of my website.

The functions works well to certain extend. I need to make sure that when a user is updated that a repeat username is not used, and display a message that a particular user already exist.

I have that functionality in my function, however, this part of the code is not executed and I keep getting the error message: Duplicate entry ‘b’ for key ‘username’. I also need to keep intact any part of the content that’s not updated, i.e., password not changed, etc.

Here’s the code: [php]function editUser($userUsername, $userPassword, $userEmail, $userRealname, $id){
//select users to see if they exist
$query = mysql_query("SELECT * FROM authorized_users WHERE username=’$userUsername’ ") or die(mysql_error()) ;
if (mysql_num_rows($query) >= 1 )
{
/* Username already exists /
echo “

Username already exists”;
echo ‘

Please Go Back and complete the form
’;
echo ‘’;
}
else
{
/

Username doesn’t exist */

$query = mysql_query("UPDATE authorized_users SET username ='$userUsername', password = '$userPassword', email='$userEmail', realname='$userRealname' ") or die (mysql_error());
echo '<p><p><b> 1 User Added</b>';
 echo '<META HTTP-EQUIV="Refresh" CONTENT="4; URL=users_authorized.php">';
}

}
[/php]

Thanks in advance for your help.

You need to somehow identify which of user record do you want to update in your sql UPDATe query. Probably with the id field - do you have such in your authorized_users table? If not, use the ‘username’ field with old value, like this:
[php]mysql_query(“UPDATE authorized_users SET username =’$userUsername’ WHERE username = ‘$oldUsername’”) or die (mysql_error());[/php]

Sure, you’ll need to add $oldUsername parameter to your editUser() function arguments.

I am sorry, I tried to insert a tab in my code and ended submitting before I was ready. Here we go again…


thanks for your help, phpHelp.

I am not having issues updating the users. The main issue that I am having is don’t have a way to make sure an existing username is not used in the database.

Also I’d like to keep intact information that’s not being changed. This is how everything is built:

1) a file called editUsers with the HTML form:
[php]<?php
include (‘includes/functions.php’);
$user = getUser($_GET[‘id’]);
?>

<tr>
	<td> <label for="userPassword">Password</label></td>
    
	<td> <input name="userPassword" type="text" class="editUserform_HL" onFocus="this.value='';this.onfocus=null;" value="<?php echo $user['password'];?>" size="33" maxlength="32" ></td>
    
</tr>

 <tr>
	<td> <label for="userEmail">e-Mail</label></td>
    <td> <input type="text" name="userEmail" value="<?php echo $user['email'];?>" class="editUserform"  size="33" maxlength="32" ></td>
</tr>

<tr>
	<td> <label for="userRealname">Real Name</label></td>
    <td> <input type="text" name="userRealname" value="<?php echo $user['realname'];?>" class="editUserform"  size="33" maxlength="32"></td>
</tr>

<tr>
	<td>&nbsp;</td>
	<td align="center"><input name="submit" type="submit" value="Send"></td>
  
</tr>

<tr>
	<td align="center"><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
  
</tr>
Username
<?php echo '
Go Back to Users';?>
[/php]

2) a File Called doEditUser which is where the form is processed:
[php]<?php
include(‘includes/functions.php’);

//create short varaibles
$submit = $_POST[‘submit’];
$userUsername = mysql_real_escape_string($_POST[‘userUsername’]);
$userPassword = mysql_real_escape_string($_POST[‘userPassword’]);
$userEmail = mysql_real_escape_string($_POST[‘userEmail’]);
$userRealname = mysql_real_escape_string($_POST[‘userRealname’]);
$id = mysql_real_escape_string($_POST[‘id’]);
//md5($userPassword)

if (isset($submit)){

//check if category name is entered. Description is no requireD, so we don't check it here
if (isset($_POST['userUsername'])){
	editUser($userUsername, (md5($userPassword)), $userEmail, $userRealname, $id);
	//header('location:users_authorized.php');
	} else {
		echo 'Please Set a Username!';
		include ('editUsers.php');
		}

} 

?>[/php]

  1. And finally, a file called functions, which contain the referenced function called editUser()
    [php]function editUser($userUsername, $userPassword, $userEmail, $userRealname, $id){
    //select users to see if they exist
    $query = mysql_query(“SELECT * FROM authorized_users WHERE username=’$userUsername’”) or die(mysql_error()) ;
    if (mysql_num_rows($query) >= 1 )
    {
    /* Username already exists /
    echo “

    Username already exists”;
    echo ‘

    Please Go Back and complete the form
    ’;
    echo ‘’;
    }
    else
    {
    /

    Username doesn’t exist */
    //if (isset($_POST[’’])){}
    $query = mysql_query("UPDATE authorized_users SET username =’$userUsername’, password = ‘$userPassword’, email=’$userEmail’, realname=’$userRealname’, id=’$id’ WHERE username=’$oldUsername’ ") or die (mysql_error());
    echo ’

    1 User Added’;
    echo ‘’;
    }
    } [/php]

I am still a bit confused how to implement it. Thanks for time.

I see you added oldUsername to the query, but you do not pass this info to the function here:
[php]if (isset($_POST[‘userUsername’])){
editUser($userUsername, (md5($userPassword)), $userEmail, $userRealname, $id);[/php]

you need to add it:
[php] editUser($userUsername, (md5($userPassword)), $userEmail, $userRealname, $id,$oldUsername);[/php]

And also populate its value… say set this as hidden field in your html form, or read from database using id as user identifier.

You say you have no problem updating user info… but in your original code, your UPDATE query would just update info for ALL users in your authorized_users table. So, either use field id (preferred, but I am not sure if you have this in your table), or use $oldUsername (but you need to pass it to your editUser() function.

Yes, I have an id field as part of my table. So specific users are pulled in to be updated. I will follow your recommendations and post back. Thanks a lot.

Hi guys. I have been battling a severe cold the last few of days.

I kept getting lots of error, and decided to start over as in the beginning. I created a free online account and posted the files there for you to see how is all working.

Go to http://javierbooks.comuf.com/administrar/ and enter the login info:
username: test
password: test

I modified the script a bit so as if someone deletes all the users, the test user is recreated automatically

Here’s where I am right now:
a) I can and delete, or modify users and posts without major problems
b) The main issue is when you are trying to edit an user. If you click on the edit link and change the text of anything there but the username, it keeps sending you to “username exist.” In other words, the script is forcing you change the username once you have clicked on the Edit link, unless you get out by going back to display all users by clicking on the (users link).

Here I am going to paste the code again as I have it. I missed one step that I for got to show you, and that’s why you were thrown off a bit when you asked if I had an ID field in my database. Here we go…

  1. First, as I said before, I have a file called functions.php, which contains all the relevant functions that are called for edit, deleting, showing, etc. I forgot to mention that there is a function called getUser($id). This function pulls any specific or selected user:
    [php]function getUser($id){
    $id = (int) $id;// TYPECASTING to avoind SLQ injections
    $query = mysql_query("SELECT * FROM authorized_users WHERE id =’$id’ ") or die(mysql_error()) ;
    return mysql_fetch_assoc($query);
    }//Get selected user so it can be updated[/php]

  2. There’s a file called editUsers.php, and this is the HTML form to update the users. Here I make a function call to the getUser($id) function to populate the form with content from MYSQL.
    [php]

<?php include ('includes/functions.php'); $user = [b]getUser($_GET['id']);[/b] ?>
<tr>
	<td> <label for="userPassword">Password</label></td>
	<td> <input name="userPassword" type="text" class="editUserform_HL" onFocus="this.value='';this.onfocus=null;" value="ENTER NEW PASSWORD HERE" size="33" maxlength="32" ></td>
</tr>

<tr>
	<td> <label for="userPassword_OLD">Old Password</label></td>
    <td><input name="userPassword_OLD" type="text" class="editUserform" value="<?php echo $user['password'];?>" size="33" maxlength="32" readonly="readonly" /></td>
</tr>

 <tr>
	<td> <label for="userEmail">e-Mail</label></td>
    <td> <input type="text" name="userEmail" value="<?php echo $user['email'];?>" class="editUserform"  size="33" maxlength="32" ></td>
</tr>

<tr>
	<td> <label for="userRealname">Real Name</label></td>
    <td> <input type="text" name="userRealname" value="<?php echo $user['realname'];?>" class="editUserform"  size="33" maxlength="32"></td>
</tr>

<tr>
	<td>&nbsp;</td>
	<td align="center"><input name="submit" type="submit" value="Send"></td>
</tr>

<tr>
	<td align="center"><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
</tr>

<tr>
	<td> <?php echo '<br>Go Back to <a href="users_authorized.php">Users</a>';?></td>
</tr>
Username
[/php]
  1. After the form is submitted, doEditUsers.php is called to process it. Here user inputs are escaped and the password is hashed.

[php]<?php
include(‘includes/functions.php’);
//create short varaibles
$submit = $_POST[‘submit’];
$userUsername = mysql_real_escape_string($_POST[‘userUsername’]);
$userPassword = mysql_real_escape_string($_POST[‘userPassword’]);
$userEmail = mysql_real_escape_string($_POST[‘userEmail’]);
$userRealname = mysql_real_escape_string($_POST[‘userRealname’]);

$id = mysql_real_escape_string($_POST[‘id’]);
//md5($userPassword)

if (isset($submit)){

//check if category name is entered. Description is no requireD, so we don't check it here
if (isset($_POST['userUsername'])){
	editUser($userUsername, (md5($userPassword)), $userEmail, $userRealname, $id);
	//header('location:users_authorized.php');
	} else {
		echo 'Please Set a Username!';
		include ('editUsers.php');
		}
	} 

?>[/php]

A called is made to a third function editUser(), and here’s is where I am tripping. Here’s that function
4) [php]function editUser($userUsername, $userPassword, $userEmail, $userRealname,$id){
//select users to see if they exist
$query = mysql_query("SELECT * FROM authorized_users where username =’$userUsername’ ") or die(mysql_error());

		if (mysql_num_rows($query) >= 1 ){ 	
		/* Username already exists */
		 echo "<p><p><span class='current_admin'>Username already exists</span>";
		 echo '<p>Please <a href="javascript:history.go(-1)">Go Back</a> and complete the form<br>';
		 echo '<META HTTP-EQUIV="Refresh" CONTENT="8; URL=users_authorized.php">';
		 
		 } else {	 	
			$query = mysql_query("UPDATE authorized_users SET username ='$userUsername', password = '$userPassword', email='$userEmail', realname='$userRealname' WHERE id='$id' ") or die (mysql_error());
			
			echo '<p><p><b> 1 User Updated</b>';
			echo '<p>Go Back to <a href="users_authorized.php">Users</a>';
			echo '<META HTTP-EQUIV="Refresh" CONTENT="4; URL=users_authorized.php">';}
			}	[/php]
  1. One last thing I noticed is that a username is updated and nothing else is changed, the password is re-hashed, which would block the user from login in again because he would never know what the already hashed password would be rehashed to. Right now I am just getting away with it by retype the same password again, that is if I want to keep the same one.

I encourage you to test the admin panel manage users and manage posts in and out so you can better understand what I mean. Any changes made in manage post will be reflected immediately and can be viewed by clicking on the view website link at the bottom right of the tables. I have back-up of the database so I don’t worry about the changes… plus this is not the live server of the website.

I know this a mouthful, but I just wanted to break it down as much as I could. And thahks for your help phpHelp and the rest of the crew. :wink:

When you update user record… if password has not been changed by user - just do not update it in the database (you need to compare hash of new password with value stored in database for this user). Also, you’re doing redirect with META/Refresh - this is executed on user end by browser. People will stil be able to access page (say by disabling meta redirect in theor browser). You need to use header() function instead:
[php]header(‘Location: users_authorized.php’);
exit;[/php]

(but for this you will probably need to restructure your php code, so that there is no any html before header() function call.

Thanks again, phpHelp.

I fixed the password hashing issue by editing the doEditUsers.php file as follow:
[php]if (isset($submit)){

//check fields are populated
if (!$userUsername || !$userPassword || !$userEmail || !$userRealname) {
	echo '<p><p><p><p><p><p><p><span class="current_admin">You Cannot leave any empty field</span>	
	<p>Please <a href="javascript:history.go(-1)">Go Back</a> and complete the form<br>';
	} 
	
	else

if (isset($userUsername)){
		//IF IT IS AN OLD PASSWORD, DON'T HASH PASSWORD
		if($userPassword == $oldPassword){
								editUser($userUsername, $userPassword, $userEmail, $userRealname, $oldUsername, $oldPassword,$id);
								}
						
		//IF IT IS A NEW PASSWORD, HASH THE PASSWORD WITH MD5 ENVRYPTION
		if ($userPassword != $oldPassword){
		editUser($userUsername, (md5($userPassword)), $userEmail, $userRealname, $oldUsername, $oldPassword,$id);
		//header('location:users_authorized.php');
		} 		
	}
} [/php]

The only remaining issue I have is making sure a duplicate user is not used when updating the database. In fact as of now a duplicate user can’t be used as I get the error message “Duplicate entry ‘a’ for key ‘username’” when I test it. For some reason the part of the editUser() function is skipped, thus not allowing me to graciously get out of that screen.

[php]

		if (mysql_num_rows($query) > 1 ){ 	
		/* Username already exists */
		
		     echo "<p><p><span class='current_admin'>Username already exists</span>";
			 echo '<p>Please <a href="javascript:history.go(-1)">Go Back</a> and complete the form<br>';
	    	 echo '<META HTTP-EQUIV="Refresh" CONTENT="8; URL=users_authorized.php">';		 
		 	}	[/php]

I am thinking that perhaps I can solve this issue by playing with the code in the doEditUsers.php file, instead of the editUsers() function, but I haven’t figured out how to do that just yet.

The reason I am using re-direct with META/Refresh is because I needed to print the friendly messages (user updated, added, deleted, etc.) to screen, and disappear after a few seconds. I don’t know how to do this with the php header() function, if possible.

I am still stuck at this. Can anybody help, Please.
Thanks!

Sponsor our Newsletter | Privacy Policy | Terms of Service