Welcome Guest, Not a member yet? Register   Sign In
User registration with CodeIgniter
#1

[eluser]Unknown[/eluser]
Hey all. I'm new to CI, and so far very impressed. My first project with CI involves a user registration system, and I'm having some trouble with it. I have built a controller and 2 views. The controller is called Register, and the views are called register_form and register_done.

Here's my controller:
Code:
class Register extends CI_Controller {
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[16]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|sha1');
        $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
        $this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim');
        $this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|trim');
        $this->load->view('header');
        if(!$this->form_validation->run())
        {
            $this->load->view('register_form');
        }
        else
        {
            $this->load->view('register_done');
        }
        $this->load->view('footer');
    }
}

Hopefully you can see what I'm doing here. I've set the form validation rules and if the form has not been submitted, I show the form. If it's been submitted with errors, I show the form and some error messages next to the input fields, and if it all goes through okay, I show the register_done view.

Here's my register_form view:
Code:
<h1>Register with Albumbase</h1>
<p>Registering with Albumbase gives you a number of unique benifits including abilities to add and vote on albums, earn points and communicate with other users.</p>
&lt;?php $this->load->helper('form'); ?&gt;
&lt;?php echo form_open('register'); ?&gt;
    <ul id="register">
        <ul>
            <h3>Account information</h3>
            <li>
                <label for="username">Choose a username</label>
                &lt;input type="text" name="username" value="&lt;?php echo set_value('username'); ?&gt;" /&gt;
                <span class="desc">The name you'd like to be known by</span>
                &lt;?php echo form_error('username'); ?&gt;
            </li>
            <li>
                <label for="password">Pick a password</label>
                &lt;input type="password" name="password" /&gt;
                <span class="desc">The best passwords are random and more than 6 characters long</span>
                &lt;?php echo form_error('password'); ?&gt;
            </li>
            <li>
                <label for="email">Enter your valid email address</label>
                &lt;input type="text" name="email" value="&lt;?php echo set_value('email'); ?&gt;" /&gt;
                <span class="desc">We'll send you an activation email</span>
                &lt;?php echo form_error('email'); ?&gt;
            </li>
        </ul>
        <ul>
            <h3>About you</h3>
            <li>
                <label for="artist">Who's your favorite artist?</label>
                &lt;input type="text" name="artist" value="&lt;?php echo set_value('artist'); ?&gt;" /&gt;
                <span class="desc">Don't put Lady GaGa.</span>
                &lt;?php echo form_error('artist'); ?&gt;
            </li>
        </ul>
        <ul>
            <h3>Security question</h3>
            <li>
                <label for="captcha">Enter the letters you see in the image</label>
                &lt;?php $this->load->helper('captcha');
                $cap = create_captcha(array('img_path' => './captcha/', 'img_url' => 'http://localhost/captcha/', 'img_width' => 200, 'img_height' => 30));
                $data = array('captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word']);
                $query = $this->db->insert_string('captcha', $data);
                $this->db->query($query);
                echo $cap['image']; ?&gt;
                &lt;input type="text" name="captcha" /&gt;
                &lt;?php echo form_error('captcha'); ?&gt;
            </li>
        </ul>
        <ul>
            <h3 class="submit">
                &lt;input type="submit" value="Register" /&gt;
            </h3>
        </ul>
    </ul>
&lt;?php echo form_close(); ?&gt;

Everything works OK so far. What I'm having trouble doing is adding the new user to my users table in my database, and also checking whether the username/email already exists in my database. If one of those does already exist, I want to display an error under the appropriate input field saying something along the lines of "Username already in use."

Also, would I use a model for interacting with my database in this way? And one other question, is it okay to use the CAPTCHA generation code in my view like that? That's how it's done in the user guide, but it doesn't really seem to follow the MVC pattern does it?

Thanks for any help everyone, and I look forward to getting to know CI in the future Smile
#2

[eluser]Frank Rocco[/eluser]
Check the user_guide for validation callbacks.
Check if user exists in the callback function.

Code:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
#3

[eluser]toymachiner62[/eluser]
To add a user to the db, you obviously have to create the db and table, but then you can create a model similar to this:

Code:
Model My_model extends CI_Model
{
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    funtion insert_user($user) {
        $user_data = array(
            'user' = $user
        );
        if($this->db->insert('user', $user_data)) {
           return true;
        } else {
           return false;
        }
    }
}

Then in your controller you'd have something like this:
Code:
class Register extends CI_Controller {
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[16]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|sha1');
        $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
        $this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim');
        $this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|trim');
        $this->load->view('header');
        if($this->form_validation->run() == false)
        {
            $username = $this->input->post('username');
            $this->load->model('my_model');

            if($this->my_model->insert_user('$username')) {
                $this->load->view('register_done');
            } else {
                $this->load->view('register_form');
            }
        }
        else
        {
            $this->load->view('register_form');
        }
        $this->load->view('footer');
    }
}
#4

[eluser]valentia[/eluser]
Hi cideveloper,

I tried to use your code to insert data from a form to a database, but instead of inserting the data entered in the form, it inserts 0 in every field.

The function in the controller:

function thanks_fsd ()
{
if($data['success'] = true){

$insertdata = array(
'name_fd'=>$this->input->post($data['name']),
'comment_fd'=>$this->input->post($data['message']),
'email_fd'=>$this->input->post($data['reply_to'])
);

$this->load->model('model_fsd');

$this->model_fsd->create_contestant($insertdata);

$tags['title'] = 'My Title';

$this->load->view($this->session->userdata('language').'/includes/view_header',$tags);
$this->load->view($this->session->userdata('language').'/events/view_thanks_fsd');
$this->load->view($this->session->userdata('language').'/includes/view_footer');

}

}



In the model:


class Model_fsd extends CI_Model
{

function __construct()
{
parent::__construct();

}


function create_contestant($insertdata)

{
$insertdata = array(
'name_fd'=>$name_fd,
'comment_fd'=>$comment_fd,
'email_fd'=>$email_fd
);

if ($this->db->insert('event_fsd', $insertdata)) {

return true;

} else {

return false;

}

}

}


What is wrong?

Thank you in advance.
#5

[eluser]cideveloper[/eluser]
Try this in your model. You are sending an array to the model but then recreating the array with variables that are not passed to the model. Also please use code tags.
Code:
class Model_fsd extends CI_Model
{

function __construct(){
  parent::__construct();
}


function create_contestant($insertdata){

  if ($this->db->insert('event_fsd', $insertdata)) {

   return true;

  } else {

   return false;

  }

}

}
#6

[eluser]valentia[/eluser]
Thanks, I'll try...
#7

[eluser]boltsabre[/eluser]
On a side note, if everything works and the user is registered, instead of loading a view like this:
Code:
if($this->my_model->insert_user('$username')) {
                $this->load->view('register_done');
            } else {
                $this->load->view('register_form');
            }

You should use a redirect like this:
Code:
if($this->my_model->insert_user('$username')) {
                redirect('register_done');
            } else {
                $this->load->view('register_form');
            }

If you just load the register_done view if the user refreshes the page the form will submit again with the existing $_POST array of data. If you have a check for a unique email address it will fail validation and display an error, or worse if you don't have this check it will simply insert a whole new user into your table with the exact same details as when they first submitted the form.

Using redirect actually loads the PHP file again on the server, thus clearing any existing variables (ie, the superglobal $_POST array) and give you a fresh start (for want of a better expression).

There should be some documentation about this, new CI users so often run into this problem, and also with this and flashdata (to actually display a flashdata message you MUST redirect to a controller, not just load a new view in the same controller you set the flashdata).
#8

[eluser]valentia[/eluser]
Unfortunately it doesn't work, still inserts 0 in every field in the database.
#9

[eluser]boltsabre[/eluser]
Code:
function create_contestant($insertdata){
  var_dump($insertdata);
  //if ($this->db->insert('event_fsd', $insertdata)) {
  // return true;
// } else {
   //return false;
  }
What does var_dump($insertdata) return? If it's not your array of expected data to be inserted into your table then you know it's a problem with your array in your controller. If it is the expected data, then I'd check to make sure your table column names are EXACTLY the same as your array keys.
#10

[eluser]valentia[/eluser]
The code in the controller:

Code:
$insertdata = array(
            ‘name_fd’=>$this->input->post($data[‘name’]),
            ‘comment_fd’=>$this->input->post($data[‘message’]),
            ‘email_fd’=>$this->input->post($data[‘reply_to’])
          );

The column names in the table are name_fd, comment_fd, email_fd, the $data[‘name’], [‘message’], [‘reply_to’] variables are the input from the form. They are used to send the emails and in that function they work, but apparently they don't pass the value to the create_contestant function.

Also, is there a way to pass these variables to the redirect page? I tried with:

Code:
$this->load->view($this->session->userdata('language').'/includes/view_header',$tags);
$this->load->view($this->session->userdata('language').'/events/view_thanks_fsd', $insertdata);
$this->load->view($this->session->userdata('language').'/includes/view_footer');

But nothing.




Theme © iAndrew 2016 - Forum software by © MyBB