Welcome Guest, Not a member yet? Register   Sign In
Best method for sending form variables to a model ?
#1

[eluser]Mikeboy[/eluser]
Hi

Quick intro. I am going to rewrite a fairly large database-driven application which was written a few years ago in a spaghetti of php and html. I've researched a number of different MVC frameworks and have decided on CI.

All select, update, and delete queries are achieved through stored procedures (MSSQL).

I notice there are a number of ways to pass the user data to the model. However I am hoping there is a better way that I have missed.


1) Form variables into data array, send data array to model
Code:
View[
<input type="text" name="var1"/>
<input type="text" name="var2"/>
<input type="text" name="var3"/>

Controller
$data['var1'] = $this->input->post('var1');
$data['var2'] = $this->input->post('var2');
$data['var3'] = $this->input->post('var3');
$this->model->add($data);

Model
$v1 = $data['var1'];
$v2 = $data['var2'];
$v3 = $data['var3'];
$this->db->query("exec spXXX '$v1','$v2','$v3'");
The thing I don't like about this method is having to do deal with data[] array in both the model and the controller. Most of the procedures have 10+ parameters so this may be messy.


2) Read the post variables directly from the model. Guess this saves having to read them into the controller first, but, I don't know, I'd rather go through the controller.
Code:
Model
$v1 = $this->input->post('var1');
$v2 = $this->input->post('var2');
$v3 = $this->input->post('var3');


3) Slightly different, .. something like this, from the Godbit tutorial.
Code:
View
<?=form_input($var1);?>
<?=form_input($var2);?>
<?=form_input($var3);?>

Controller
$data["var1"] = array('name' => 'var1', 'id' => 'var1');
$data['var2'] = array('name' => 'var2', 'id' => 'var2');
$data['var3'] = array('name' => 'var3', 'id' => 'var3');
$this->model->add($data);

Model
$v1 = $this->input->post('var1');
$v2 = $this->input->post('var2');
$v3 = $this->input->post('var3');
$this->db->query("exec spXXX '$v1','$v2','$v3'");


Or 4) Something like:
Code:
Controller
$this->model->add($data["var1"], $data["var1"], $data["var1"]);

Model
$this->db->query("exec spXXX '$v1','$v2','$v3'");


Please, can anyone advise the optimum, recommended, most conventional way?!

Edit, I've not included any validation yet - just want to complete the form basics first.

Thanks
Mike
#2

[eluser]Rick Jolly[/eluser]
I use a variation of method #1. CI's validation can modify the $_POST array. When validating you will probably want to prep the form data. For example, I usually use "trim" to remove leading/trailing spaces. So when the validation succeeds, the $_POST array will contain the validated and prepped form data. So you could safely do this:
Code:
Controller
// if validation succeeds:
$this->model->add($_POST);

Model
$v1 = $data['var1'];
$v2 = $data['var2'];
$v3 = $data['var3'];
$this->db->query("exec spXXX '$v1','$v2','$v3'");
You could dynamically build your queries with a loop.
#3

[eluser]Mikeboy[/eluser]
Cool! Thanks Rick Smile
#4

[eluser]ywftdg[/eluser]
I have been trying to get this to work in a MVC setup, but nothing works. It works when its just in controller as:

Code:
$data['password'] = $this->input->post('password');
            $data['email'] = $this->input->post('email');
            
            $this->db->select('*');
            $this->db->where('designer.dEmail' , $data['email']);
            $this->db->where('designer.dPassword' , $data['password']);
            $this->db->from('designer');
            $query = $this->db->get();

But if I try and put this in a model/controller setup, the variables wont pass. Any suggestions on how you would flip the query on this to a model and pass the variables email and password? Then bring back to the controller for a if statement?

MY attempted MVC is:

model
Code:
function check_emailpassword($data)        {    
        $email = $data['email'];
        $password = $data['password'];
            
           $this->db->select('*');
        $this->db->where('designer.dEmail' , $email);
        $this->db->where('designer.dPassword' , $password);
        $this->db->from('designer');
        $query = $this->db->get();
        return $query->result();
       }

controller
Code:
function login()
    {

        $this->load->library('validation');
        $this->load->model('Designers_model', 'designer');
        
    
        if ($this->validation->run() == TRUE)    {
            $data['password'] = $this->input->post('password');
            $data['email'] = $this->input->post('email');
            
            $this->load->model('Designers_model', 'designer');
            $query = $this->designer->check_emailpassword($data);
            
            if ($query->num_rows() > 0) { // DB TRUE
                  redirect('designers/account');
            } else    { // QUERY FALSE
                $this->load->view('login_view');
                }
        }
        
        else    { // Validation FALSE
            $this->load->view('login_view');
        }

    }
#5

[eluser]Jilani Jidni[/eluser]
Hi

you made a mistake on function signature on the model. Try this

function check_emailpassword($posted){

}

hope this will work.
#6

[eluser]Jilani Jidni[/eluser]
I think you have not load your database. you can do this this way when you attempt to load the model

Code:
$this->load->model('Designers_model', 'designer',TRUE);

if you pass TRUE into the third parameter this will automatic load the database by default settings. To know more please read the CodeIgniter user guide.

hope this will work for you.
#7

[eluser]nmweb[/eluser]
Don't access $_POST from within the model. Model has no awareness of $_POST. Your controller can pass $_POST on to the model.
#8

[eluser]ywftdg[/eluser]
Ok, got it working. One thing though, I ended up placing my redirect in the model, is this good form? After it checks the query listed above in my model, it then says either move on, or reload the form. Is it ok to be in the model, or should this be back in the controller after the model is loaded. I ask because I couldn't get it to work in the controller, only in the model like this ->

Code:
function check_emailpassword($data)        {
        $this->load->library('session');
            
        $email = $data['email'];
        $password = $data['password'];
            
           $this->db->select('*');
        $this->db->where('designer.dEmail' , $email);
        $this->db->where('designer.dPassword' , $password);
        $this->db->from('designer');
        $query = $this->db->get();
        
        if ($query->num_rows() > 0) { // REDIRECT
            $this->session->set_userdata('designeremail', $email);
            redirect('designers/account');
        } else    {
            $this->load->view('login_view');
        }
                
       }
#9

[eluser]BobbyB[/eluser]
Hi folks,
I am trying to pass variables to a model, and tried the above solutions.
But I must be doing sth wrong.

In my controller I got:
Code:
class Freebies extends Controller {

    function Freebies()
    {
        parent::Controller();
        $this->load->helper(array('form', 'url'));
    }
    
    function index()
    {

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

$cat = $this->input->get_post('category', TRUE);

$this->model->add($cat);

$data['freebies'] = $this->Get_freebies->getselect();

$this->load->view('freebies_view', $data);
}
}

It says "Fatal error: Call to a member function on a non-object..."
I am trying to pass a "post" variable from a form to the controller and finally to the model.

Can I pass variables to only a single function(getselect()Wink in a model or will they be passed to all the functions in the model?

Thaks in advance!
#10

[eluser]crumpet[/eluser]
To above : i think your model needs to be in lower case like this $this->get_freebies->method();

On the subjet:

If you name consistently through your application so your form fields and database fields are the same then you can do this:
view:
Code:
<input type="text" name="var1"></input>
<input type="text" name="var2"></input>
<input type="text" name="var3"></input>
controller:
Code:
//Validate of course.. then when data is santized:
$this->load->model('Product_Model', 'products', TRUE);
if($this->products->save($_POST)){
   redirect('successPage');
}else{
   die('failed to save product');
}
model:
Code:
function save($data){
   $product = (object) $data;
   //determine whether we are creating a new entry or saving over an old one
   return isset($data->productID) ? $this->_update($product) : $this->_create($product);
}
function _create($data){
   //if we are successful return the new id otherwise return false
   return $this->db->insert('products', $data) ? $this->db->insert_id() : FALSE;
}
function _update($data){
   $this->db->where('productID', $data->productID);
   return $this->db->update('products', $data);
}

That is for something like adding a new product with many fields.. but for login with only two fields I thing the best thing to do is this:
Controller
Code:
function login(){
//validaiton code...

if($this->validation->run(){
//do stuff
}
else{ //lets log in
   $this->load->model('Users_Model', 'users', TRUE);
   if ($this->users->login($_POST['username'], md5($_POST['password']))){
      //set cookies in the controller
      //success page
   }
   else{
      die('failed');
   }
}


}
Model
Code:
function login($username, $password){
   $password = md5($password);
   $this->db->where('username', $username);
   $this->db->where('password', $password);
   $query = $this->db->get('users');
   return $this->db->num_rows() > 0;
}




Theme © iAndrew 2016 - Forum software by © MyBB