Jump to content

Asigning User(s) To Group Upon Registration


Azercii

Recommended Posts

Firstly, I'm new to PhP, so I truly apologize if I'm a headache and make you want to put a fist through your screen :happy-04: haha

 

I'm slowly creating a community site, and need some advice on something, if I may? I would like users to be put into the user_group database as "member" by default upon registering, but I can't seem to get my head round it  :-\

 

 

 

Currently, I have a table on my "memberlist" page with;

<td width="115px" class="Members" align="center"><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>

<td width="115px" class="Members" align="center"><?php echo htmlentities($row['user_group'], ENT_QUOTES, 'UTF-8'); ?></td>

But I'm having to edit the database each time a new user signs up because it's not in-putted via the form  :-\

 

 

 

 

 

(Forgive me if I now seem a little newbiie)

 

I was thinking that it might be an if function on the register page? Something like;

 

 

 

If the user clicks submit, and the registration is successful, input member into the users user_group field

 

 

 

But in PhP obviously  :tease-03: I already have user_level in my database, which is default to 0 anyway, I would just like the users to have a "group" like forums  :sweat:

 

 

 

 

 

How would I go about this? I'm okay with creating databases, and/or inputting data into them via MySQL. PhP might need a little dumb down though  :confused:

Link to comment
Share on other sites

You have a process around creating the user. That process may entail a confirmation process or something as well. Just determine at what point in that process that you want to add them to the group and, well, add them by running a query. You could do it right after creating the user int he database if you want. This is not something you would handle through the form/HTML.

Link to comment
Share on other sites

You have a process around creating the user. That process may entail a confirmation process or something as well. Just determine at what point in that process that you want to add them to the group and, well, add them by running a query. You could do it right after creating the user int he database if you want. This is not something you would handle through the form/HTML.

 

 

Aah okay, I thought it had to be done via the submission form. As for the query, how would I phrase it?

Link to comment
Share on other sites

I can't seem to find an edit option to add to my previous post, sorry.

 

I've tried;

$query = " 
            INSERT INTO users ( 
                username, 
                password, 
                salt, 
                email,
		user_group 
				 
            ) VALUES ( 
                :username, 
                :password, 
                :salt, 
                :email,
		:Member 
            ) 
        "; 

To which I receive this error;

 

 

 

Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Link to comment
Share on other sites

password is a reserved word.

 

 

That's not where the error lies, that line works fine as it's inputting the users password into the database. I eventually got round the errors for all this by defaulting it to say Member and adding a drop-down list for the users to select "Member" from, they're not linked but they'll think it is

Edited by Azercii
Link to comment
Share on other sites

Kinda little confused with the question. drop-down box? wah! use hidden field with value of member... well if you got it working that's cool too.

 

Regards to the error: Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

 

Think you should try what TRQ suggested was that the password is reserved, change it.

Link to comment
Share on other sites

Kinda little confused with the question. drop-down box? wah! use hidden field with value of member... well if you got it working that's cool too.

 

Regards to the error: Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

 

Think you should try what TRQ suggested was that the password is reserved, change it.

 

I would prefer a better solution than the one I came up with haha  :tease-03:

 

 

 

That error was linked to the added parameters I told it to include, I didn't include them further down the code so it mismatched. The password row has always worked and is fine for inputting the users pass into the table without errors, why would I need to change it? :confused:  

 

 

You can view the site here: http://cloudgaming.byethost7.com/

Edited by Azercii
Link to comment
Share on other sites

I don't see how we can help you with the information provided. You've stated you are using a database, but the only code you are showing is HTML - which has nothing to do with the problem as I understand it.

 

You've stated you have a "registration process". I have to assume that this process creates a record in the database associated with the user.

 

You stated the problem as you want that new users to be automatically put in the "user_group database as 'member' by default". You further stated "I'm having to edit the database each time a new user signs up because it's not in-putted via the form". This is a business rule you want to implement. The "form" has nothing to do with this.

 

As I stated previously, you (by 'you' I mean YOU) need to implement some additional logic in the code that creates the user record to also add a record in the user_group table. You've shown zero code related to the user creation/registration process nor given any details on the table structures. Therefore, the help that was provided was generic in nature.

 

But, I am feeling generous so I will provide the following mock example. This assumes the user table has an auto-insert incrementing ID

//Run query to insert user record
$query = "INSERT INTO users (name, email, birthdate)
          VALUES ('$name', '$email', '$bdate')";
$result = mysqli_query($link, $query);
$user_id = mysqli_insert_id($link); //Get id of last inserted record

//Run query to add record to user_group table for new user
$query = "INSERT INTO user_group (user_id, group)
          VALUES ($user_id, 'member')";
$result = mysqli_query($link, $query);
Edited by Psycho
Link to comment
Share on other sites

If you needed to see a different part, or if I got something wrong, you could have just said so before in the earlier post.. I did declare that I'm new to PhP, I'm not amazing at all of this like everyone else seems to be  :sweat:

 

 

Below is the PhP for the registration page, I've removed the entities I added earlier so we can start from scratch here.

<?php 

    // First we execute our common code to connection to the database and start the session 
    require("common.php"); 
     
    // This if statement checks to determine whether the registration form has been submitted 
    // If it has, then the registration code is run, otherwise the form is displayed 
    if(!empty($_POST)) 
    { 
        // Ensure that the user has entered a non-empty username 
        if(empty($_POST['username'])) 
        { 
            // Note that die() is generally a terrible way of handling user errors 
            // like this.  It is much better to display the error with the form 
            // and allow the user to correct their mistake.  However, that is an 
            // exercise for you to implement yourself. 
            die("Please enter a username."); 
        } 
         
        // Ensure that the user has entered a non-empty password 
        if(empty($_POST['password'])) 
        { 
            die("Please enter a password."); 
        } 
         
        // Make sure the user entered a valid E-Mail address 
        // filter_var is a useful PHP function for validating form input, see: 
        // http://us.php.net/manual/en/function.filter-var.php 
        // http://us.php.net/manual/en/filter.filters.php 
        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) 
        { 
            die("Invalid E-Mail Address"); 
        } 
         
        // We will use this SQL query to see whether the username entered by the 
        // user is already in use.  A SELECT query is used to retrieve data from the database. 
        // :username is a special token, we will substitute a real value in its place when 
        // we execute the query. 
        $query = " 
            SELECT 
                1 
            FROM users 
            WHERE 
                username = :username 
        "; 
         
        // This contains the definitions for any special tokens that we place in 
        // our SQL query.  In this case, we are defining a value for the token 
        // :username.  It is possible to insert $_POST['username'] directly into 
        // your $query string; however doing so is very insecure and opens your 
        // code up to SQL injection exploits.  Using tokens prevents this. 
        // For more information on SQL injections, see Wikipedia: 
        // http://en.wikipedia.org/wiki/SQL_Injection 
        $query_params = array( 
            ':username' => $_POST['username'] 
        ); 
         
        try 
        { 
            // These two statements run the query against your database table. 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) 
        { 
            // Note: On a production website, you should not output $ex->getMessage(). 
            // It may provide an attacker with helpful information about your code.  
        
        } 
         
        // The fetch() method returns an array representing the "next" row from 
        // the selected results, or false if there are no more rows to fetch. 
        $row = $stmt->fetch(); 
         
        // If a row was returned, then we know a matching username was found in 
        // the database already and we should not allow the user to continue. 
        if($row) 
        { 
            die("This username is already in use"); 
        } 
         
        // Now we perform the same type of check for the email address, in order 
        // to ensure that it is unique. 
        $query = " 
            SELECT 
                1 
            FROM users 
            WHERE 
                email = :email 
        "; 
         
        $query_params = array( 
            ':email' => $_POST['email'] 
        ); 
         
        try 
        { 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) 
        { 
            die("Failed to run query: " . $ex->getMessage()); 
        } 
         
        $row = $stmt->fetch(); 
         
        if($row) 
        { 
            die("This email address is already registered"); 
        } 
         
        // An INSERT query is used to add new rows to a database table. 
        // Again, we are using special tokens (technically called parameters) to 
        // protect against SQL injection attacks. 
        $query = " 
            INSERT INTO users ( 
                username, 
                password, 
                salt, 
                email,
				 
            ) VALUES ( 
                :username, 
                :password, 
                :salt, 
                :email,
            ) 
        "; 
         
        // A salt is randomly generated here to protect again brute force attacks 
        // and rainbow table attacks.  The following statement generates a hex 
        // representation of an 8 byte salt.  Representing this in hex provides 
        // no additional security, but makes it easier for humans to read. 
        // For more information: 
        // http://en.wikipedia.org/wiki/Salt_%28cryptography%29 
        // http://en.wikipedia.org/wiki/Brute-force_attack 
        // http://en.wikipedia.org/wiki/Rainbow_table 
        $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); 
         
        // This hashes the password with the salt so that it can be stored securely 
        // in your database.  The output of this next statement is a 64 byte hex 
        // string representing the 32 byte sha256 hash of the password.  The original 
        // password cannot be recovered from the hash.  For more information: 
        // http://en.wikipedia.org/wiki/Cryptographic_hash_function 
        $password = hash('sha256', $_POST['password'] . $salt); 
         
        // Next we hash the hash value 65536 more times.  The purpose of this is to 
        // protect against brute force attacks.  Now an attacker must compute the hash 65537 
        // times for each guess they make against a password, whereas if the password 
        // were hashed only once the attacker would have been able to make 65537 different  
        // guesses in the same amount of time instead of only one. 
        for($round = 0; $round < 65536; $round++) 
        { 
            $password = hash('sha256', $password . $salt); 
        } 
         
        // Here we prepare our tokens for insertion into the SQL query.  We do not 
        // store the original password; only the hashed version of it.  We do store 
        // the salt (in its plaintext form; this is not a security risk). 
        $query_params = array( 
            ':username' => $_POST['username'], 
            ':password' => $password, 
            ':salt' => $salt, 
            ':email' => $_POST['email'],
			); 
         
        try 
        { 
            // Execute the query to create the user 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) 
        { 
            // Note: On a production website, you should not output $ex->getMessage(). 
            // It may provide an attacker with helpful information about your code.  
            die("Failed to run query: " . $ex->getMessage()); 
        } 
         
        // This redirects the user back to the login page after they register 
        header("Location: login.php"); 
         
        // Calling die or exit after performing a redirect using the header function 
        // is critical.  The rest of your PHP script will continue to execute and 
        // will be sent to the user if you do not die or exit. 
        die("Redirecting to login.php"); 
    } 
     
	
			
			
?> 

Here is my Table;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` char(64) COLLATE utf8_unicode_ci NOT NULL,
  `salt` char(16) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `user_level` int( NOT NULL,
  `user_group` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=12 ;
Link to comment
Share on other sites

I created the table and inserted the snippet you sent, with some adjustments as it was telling me to check my syntax around those lines. Then I got;
 
 

 

Error: number of bound variables does not match number of tokens

 

 

 

 

 

 

So, after you insert the user record, get the user ID and insert another record into the user_group table as I showed above. Sorry, but I have to ask, did you write that code or did you simply copy/paste that from a tutorial?

 

All my pages use this PhP: http://forums.devshed.com/php-faqs-stickies-167/program-basic-secure-login-system-using-php-mysql-891201.html

 

Minus the table, I created a new table for it as I couldn't see any of the users with the one provided  :-\

 

 

I thought I'd start with a pre-made system and make small changes where needed to get practice at changing values etc. It isn't going too great, I admit that haha apologies if my previous post seemed a little, moody? I can't find video tutorials for the things I seem to want to do, and previous sites have given me the negative attitude because I'm new to it all  :sweat:

Link to comment
Share on other sites

Hmm, going back to the link you posted, did you read through the article and write out the code to ensure you understood every line of code or did you just copy/paste the code? I think that is why you are getting negative reactions. It appears you are taking working code and then trying to add additional logic without really understanding the current logic. You are trying to run before you know how to walk.

 

That is why my earlier reply was so terse. The question you asked would be extremely basic for someone who had already created code to complete a registration process. Sort of like someone asking "Hey I just built this house and want to put a bay window into the living room wall". Most people would be "WTF, you built a house and you can't figure out how to put in a window <scratches head>".

 

And, the way you are expressing things shows a great lack of understanding of how all the processes work - as I stated previously about the form not needing to have a member field. I'm not sure I can really help you at this point except to add the following:

 

1. If users will only ever belong to one group, then add a group field to the user table and set the default value to 'members' - instead of using a separate table. That will solve your immediate need. You don't need a form field or even change the queries for the registration process as the value will be automatically set with the default value when new records are created. You can then create an administrative page to allow you to change the membership of users later.

Link to comment
Share on other sites

I did indeed just take the code and place it in, I left the comments in so I can look over it and learn each piece, but the whole subject still confuses me. I might have to go back to square one and learn little by little, thanks for the help though :) apologies if I was a pain in the rear aha

Link to comment
Share on other sites

Least you are giving it ago Azercii. Every body shares code that is a norm with development, use a pen and paper before you start coding to workout what you want to build/do before you start hacking away.

 

Some resources I recommend:

Next time you ask a question might be an idea do share the code at your initial post of question to help phpfreaks help you, keep it simple (KISS principle), think about the question first and begin, everyone is learning and finding new things everyday so don't be scared to ask a question. The forum is for helping each other, even the guru's still use references and ask questions. I myself am newb and I learn by reading these forum posts and research and practise.

 

Have fun coding!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.