Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Shane McC
Shane McC
3,005 Points

Codeigniter Form Validation?

Hi Everyone,

I have a question regarding form validation using codeigniter. After a user presses the "submit" button they are getting the intended error messages but I'm also getting a error message (below). The values that are displaying the error messages are hidden. I don't believe that's the culprit because I tried the syntax without the values being hidden and it didn't work. What am I doing wrong? Thanks everyone.

Error Messages

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: id
Filename: views/view_information.php
Line Number: 46
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: year
Filename: views/view_information.php
Line Number: 48
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: make
Filename: views/view_information.php
Line Number: 49
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: model
Filename: views/view_information.php
Line Number: 50

My View

<style type="text/css" media="screen">
label{display: block}
</style>

<?php
echo (isset($error)) ? $error : "";
if(isset($carprices) && !is_null($carprices))
{
   echo "Car# " . $carprices[0]->id . "<br />";
   foreach ($carprices as $prices)
   {
      echo 'ID Of Vehicle: '.$prices->id.'<br>';
      echo 'Year: '.$prices->year.'<br>';
      echo 'Make: '.$prices->make.'<br>';
      echo 'Model: '.$prices->model.'<br>';
      echo '<hr>';

      $id = $prices->id;
      $year = $prices->year;
      $make = $prices->make;
      $model = $prices->model;
      echo "$id".'<br>';
   }
}

/*
   foreach($updateprices as $row){
      $id = $row->id;
      $year = $row->year;
      $make = $row->make;
      $model = $row->model;
   }
*/

echo form_open('site/form_validate_cars'); 
echo validation_errors();

$data = array(
   'cardescription_id'    => "$id",
   'caruser_id' => "5", // hard-coded in
   'year'  => "$year",
   'make'  => "$make",
   'model' => "$model"
);

echo form_hidden($data);

echo form_label('Value:','value');

$data = array(
   'name' => 'value',
   'id' => 'value',
   'value' => set_value('value')
);

echo form_input($data);

// -----------------

echo form_label('Exterior Color:','exterior_color');

$data = array(
   'name' => 'exterior_color',
   'id' => 'exterior_color',
   'value' => set_value('exterior_color')
);

echo form_input($data);

// -----------------

echo form_label('Interior Color', 'interior_color');

$data = array(
   'name' => 'interior_color',
   'id' => 'interior_color',
   'value' => set_value('interior_color')
);

echo form_input($data);

// -----------------

echo form_label('Mileage:','mileage');

$data = array(
   'name' => 'mileage',
   'id' => 'mileage',
   'value' => set_value('mileage')
);

echo form_input($data);

// -----------------
// removed echo-only <tr>s on fuel type, state and transmission
// -----------------

echo form_label('State:','state');

$data = array(
   'Texas' => 'Texas',
   'California' => 'California',
   'Florida' => 'Florida',
   'Nevada' => 'Nevada'
);

echo form_dropdown('State',$data,'California');
echo '<br>';
echo form_submit('SubmitDealerInfo','Submit!');
echo form_close();
?>

Site Controller

public function form_validate_cars()
{
 $this->load->library('form_validation');  

     $this->form_validation->set_rules("value", "<b>Value</b>", "trim|required|is_numeric|xss_clean");
     $this->form_validation->set_rules("exterior_color", "<b>Exterior Color</b>", "trim|required|xss_clean");
     $this->form_validation->set_rules("interior_color", "<b>Interior Color</b>", "trim|required|xss_clean");
     $this->form_validation->set_rules("mileage","<b>Mileage</b>","trim|required|is_numeric|xss_clean");

     if ($this->form_validation->run() == FALSE)
      {   

         $data['error'] = "Please fill out proper data";
       $this->load->view('view_pricing_information', $data); 
     } 
      else 
      {

        $this->load->model('model_data');
        $this->model_data->add_new_value();
        redirect('/site/thanks');

      }
 }
James Barnett
James Barnett
39,199 Points

For intermediate questions like this, you might get a better response over on Stack Overflow.

Shane McC
Shane McC
3,005 Points

Hi James,

Thanks for the reply. I tried over there and know one seems to know either.

2 Answers

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

(Good catch on changing the double quotes to single quotes to avoid that error. Sorry about that! You can now remove that.)

The problem is that the $id variable doesn't exist after clicking Submit, but your code assumes it does. An easy way to get rid of the error is to create the variable at the top of the file.

if (!isset($id)) $id = "";

You can do the same for the other variables like $year, etc.

That should get rid of those warnings, but it may or may not address the problem. It's possible that just creating these empty values at the top will be sufficient, but it's equally possible that your code really needs those variables to have real values for it to work right. I'm afraid I cannot tell how the framework is setting all the variables and what your code is trying to accomplish.

If simply setting the variables doesn't work, you need to figure out where the breakdown is happening. When you first load the page, you are calling something like the view method in the controller. When you click submit, you are calling something like the edit method in the controller. You may be setting some variable in the view method that you are not setting in the edit method, and then your view code may need that. You'd have to figure out the best way to get that variable set in the other method. It looks to me like $carprices is the culprit, but I can't quite tell for sure.

Does that help at all?

Shane McC
Shane McC
3,005 Points

Hi Randy,

Thanks for taking the time to help em out here. Your above syntax solution did help but if a user presses "submit" and get presented with error messages the value of ID is lost, which is a problem but as for the error messages they are gone!

But I think I may have found a work around to the problem. I think CI Flashdata might be a better soltion to my problem. I was looking into it today and I think that might be the right move to make. What do you think? I'm not sure if your familiar with CI flashdata but do you think it's the right move to make? Either way, I'll work through it and figure it out.

http://ellislab.com/codeigniter/user-guide/libraries/sessions.html (a little more of than half way down)

Thanks again Randy!

Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

I'm not that familiar with it, but I am familiar with sessions and session-like behavior. Whether or not this kind of solution is the right approach depends on what this data is. When they first visit the page, you seem to have the data. Where are you getting it from? Why can't you get it from the same place on this second screen?

Shane McC
Shane McC
3,005 Points

Randy,

This is how I'm extracting the data.

I make a function in my model_data (which handles all database information. extracting, deleting, updating etc.. all database info. is handled in my model_data)

The below syntax gets the ID, year, make and model

function display_car_to_insert_price($id)
{
 $this->db->select('id,year,make,model');
 $query = $this->db->get_where('tbl_car_description',
 array(
  'id' => $id)
 );
  if($query->num_rows()) return $query->result();
  return null;
}

The next step is the site controller. The site controller basically does all of the "heavy" lifting of the website. Form validation, new member registration, etc .....

The below syntax gets data from the function above display_car_to_insert_price($id) and displays it in the view.

    public function update_price_of_car($id)
    {

if (($this->session->userdata('is_logged_in') == 1)){

if(is_null($id)) return false;
$this->load->model('model_data');
    $data['updateprices'] = $this->model_data->display_car_to_insert_price($id);
$this->load->view('view_pricing_information',$data);

} else {
  // maybe load another view and carry the values over?
  echo anchor('site/login', 'Login!');

The last step is the view. My view is called view_pricing_information.php. The view displays all of the information that being extracted from the database onto my website. I'm putting the "updateprices" into an array. Below is my entire syntax for my view. It's rather long but the first approx 65 lines are the most important. Tell me what you think. Thanks.

  <style type="text/css" media="screen">
  label{display: block}
 </style>

 <?php

  $userid = $this->session->userdata('id').'<br>';
  // https://teamtreehouse.com/forum/codeigniter-form-validation
  if (!isset($id)) $id = "";

   echo 'This is the ID of the User = '."$userid".'<br>';

   echo (isset($error)) ? $error : "";

     if(isset($updateprices) && !is_null($updateprices))
     {
       echo "Car# " . $updateprices[0]->id . "<br />";

   foreach ($updateprices as $prices)
       {
   echo 'ID Of Vehicle: '.$prices->id.'<br>';
   echo 'Year: '.$prices->year.'<br>';
   echo 'Make: '.$prices->make.'<br>';
   echo 'Model: '.$prices->model.'<br>';
   echo '<hr>';

   $id = $prices->id;
   $year = $prices->year;
   $make = $prices->make;
   $model = $prices->model;
   echo "$id".'<br>';

       }
     }

   echo form_open('site/form_validate_cars'); 

   // print_r($this->session->flashdata('test'));

   echo validation_errors();

      if(!isset($updateprices) || is_null($updateprices)) {
       echo 'Bummer! $carprices doesn\'t exist any more.'.'<br>';
       }

   if(!isset($updateprices) || is_null($updateprices)) {
      echo 'Bummer! $carprices doesn\'t exist any more.'.'<br>';
      }

   if(!isset($updateprices) || is_null($updateprices)) {
       echo "Bummer! doesn't exist any more.";
       }


   $data = array(
          'cardescription_id'    => 
          "$id", // this would have to be the ID of the vehicle in the database
          'caruser_id' => 
          "$userid" //  number of the user
        );

       echo form_hidden($data);


   echo form_label('Value:','value');

   $data = array(
    'name' => 'value',
    'id' => 'value',
    'value' => set_value('value')
   );

   echo form_input($data);

   // -----------------

   echo form_label('Exterior Color:','exterior_color');

   $data = array(
    'name' => 'exterior_color',
    'id' => 'exterior_color',
    'value' => set_value('exterior_color')
   );

   echo form_input($data);

   // -----------------

   echo form_label('Interior Color', 'interior_color');

   $data = array(
    'name' => 'interior_color',
    'id' => 'interior_color',
    'value' => set_value('interior_color')
   );

   echo form_input($data);

   // -----------------

   echo form_label('Mileage:','mileage');

   $data = array(
    'name' => 'mileage',
    'id' => 'mileage',
    'value' => set_value('mileage')
    );

   echo form_input($data);

   // -----------------

  echo '<br>';

  echo form_label('Engine:','engine');

  $data = array(
   '4Cyl' => '4Cyl',
   '6Cyl' => '6Cyl',
   'V8' => 'V8'
  );

  echo form_dropdown('engine',$data,'4Cyl');

  // -----------------

  echo '<br>';

  echo form_label('Transmission:','transmission');

  $data = array(
   'Automatic' => 'Automatic',
   'Standard' => 'Standard'
  );

  echo form_dropdown('transmission',$data,'Automatic');

  // -----------------

  echo '<br>';

  echo form_label('Gas Type:','gas_type');

  $data = array(
   'Gasoline' => 'Gasoline',
   'Diesel' => 'Diesel',
   'Electric' => 'Electric'
  );

  echo form_dropdown('gas_type',$data,'Gasoline');

  // -----------------

  echo form_label('State:','state');

  $data = array(
   'Texas' => 'Texas',
   'California' => 'California',
   'Florida' => 'Florida',
   'Nevada' => 'Nevada'
  );

  echo form_dropdown('State',$data,'California');

  echo '<br>';

  echo form_submit('SubmitDealerInfo','Submit!');

  echo form_close();

      ?>
Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

Where is update_price_of_car() getting called? I'm guessing this is getting called in a controller somewhere.

Shane McC
Shane McC
3,005 Points

Yes Randy, it's getting called in my "Site Controller"

Below is a condensed version of my "Site Controller"

Please advise. Thanks again, appreciate the help!

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Site extends CI_Controller {

public function update_price_of_car($id)
{

if (($this->session->userdata('is_logged_in') == 1)){

if(is_null($id)) return false;
$this->load->model('model_data');
    $data['updateprices'] = $this->model_data->display_car_to_insert_price($id);
$this->load->view('view_pricing_information',$data);

} else {
  // notes to myself: maybe load another view and carry the values over?
  echo anchor('site/login', 'Login!');
}
}
Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

I think this is where the function gets defined, not where it gets called. Do you have code in a function in here named "edit" or something that call this function? Or is the framework calling this function automatically because the action is "update_price_of_car"?

Shane McC
Shane McC
3,005 Points

Hi Randy,

I actually found a work around to this issue I was having. Note: it's the not greatest solution but it works. I think ultimately my solution lays with CI flash data.

This is what I did (not sure why I didn't think of this before) but the error messages I'm displaying in another view.

Part of my form if ($this->form_validation->run() == FALSE) {
$this->load->view('view_error_information', $data); }

View_error_information view <?php if (($this->session->userdata('is_logged_in') == 1)){ echo (isset($error)) ? $error : ""; echo validation_errors(); } else { echo anchor('site/login', 'Login!'); }
?>

Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

Sorry I wasn't more help: I just couldn't figure out enough from the code you posted to be helpful. Glad you got it working!

Shane McC
Shane McC
3,005 Points

You were def. helpful!

Thanks again Randy!

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

It sounds like you have a variable that's not defined named $id. Is it happening with this line?

'cardescription_id'    => "$id",

If you don't have a variable $id, this would error.

Shane McC
Shane McC
3,005 Points

Hi Randy,

Thanks for the reply. I'm defining my variables in the if statement.

   $id = $prices->id;
   $year = $prices->year;
   $make = $prices->make;
   $model = $prices->model;

When I use those variables in the array they aren't working. I'm not sure why?

Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

If the $carprices variable is not set, then that code that defines the variable is not executed. When you encounter the error, does the $carprices variable have a value?

Shane McC
Shane McC
3,005 Points

Randy,

Initially the variable $carprices is set. I'm confident it's set because I can see the year, make, model and ID of the vehicle. I'm only getting the error message when I click "submit" and the same view is loaded.

"When you encounter the error, does the $carprices variable have a value?"

No, the it's saying it's the variable is undefined (error message below). How can it be defined one second and literally one second later (after I click submit) it becomes undefined? I don't understand that.

Below is the error message. I'm only displaying one error message because I'm getting the same exact error message for year, make and model.

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: id

Filename: views/view_pricing_information.php

Line Number: 55

Thanks, any help would be greatly appreciated.

Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

It looks to me like the $carprices variable doesn't exist any more. When someone clicks Submit, I suspect the page is refreshing. The variable might exist when the page first loads but might not exist after the Submit button is clicked.

How about this? Would you mind trying something for me? You have two lines of code that looks like this:

...
echo validation_errors();

$data = array(
...

In between these two blocks of code, can you add the following code?

...
echo validation_errors();

if(!isset($carprices) || is_null($carprices)) {
    echo "Bummer! $carprices doesn't exist any more.";
}

$data = array(
...

With that code in place, what happens when you get the CodeIgniter "A PHP Error was encountered" error? Do you see this new message?

Shane McC
Shane McC
3,005 Points

Hi Randy,

My apol. for the my delayed response.

I tried your syntax, I'm still getting the error messages like I said in my previous reply when I click "submit" but now I'm also getting your echo message of "Bummer! $carprices doesn't exist any more." before I even click "submit". What should I do next?

Thanks Randy, Shane

PS. I had to make one small change to your syntax.

I took the syntax echo "Bummer! $carprices doesn't exist any more.";

and changed it to this echo 'Bummer! $carprices doesn\'t exist any more.';

I reason why I had to change it from single quotes to double quotes is because I was getting the below error message

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: carprices

Filename: views/view_pricing_information.php

Line Number: 62