• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie Problem with Foreach

#1
[eluser]Leovenous[/eluser]
Hello. I'm running a new CI install, so latest version.

Be forewarned, I have a lot to learn but I really want to "get it". I have some experience in MCV... its just programming, syntax and OOP that gets me.

What I want to accomplish is have my simple 3-field form take information, flash a confirmation, and add their name as the last-submitter.

Something is awry.

My model (don't laugh) is stealer.php
Code:
<?php
class Stealer extends model {

    function addInterest($data) {
        $this->db->insert('interest', $data);
        return;
    }

    function addCache($jett) {
        $this->db->insert('cache', $jett);
        return;
    }
    
    function getLastSignup() {
        $this->db->get('cache');
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $q = $this->db->get('cache');
        if($q->num_rows() > 0) {
          foreach ($q->result() as $row) {
            $data[] = $row;
          }
        return $data;
        }
    }
}

In the above I realized that I don't need the 'cache' table at all. I could snatch the name of the most recent signer from the signer list (duh moment). That's easy enough to change in the model, but I'm not sure how that would play out in the controller.

My controller is prerelease.php. Note that "pre" is for the view: pre.php. I'll include only the pertinent functions:
Code:
function index()
    {
        $data['row'] = $this->stealer->getLastSignup();
        //echo $data;
        //die();
        $this->load->view('pre', $data);

    }

    public function submit() {

        if ($this->_submit_validate() === FALSE) {
          $this->index();
          return;
        }

        $data = array(
        'fname' => $this->input->post('fname'),
        'email' => $this->input->post('email'),
        'zipc' => $this->input->post('zipc')
        );
        $name = $this->input->post('fname');
        $jett = array('latestu' => $name);
        $this->stealer->addInterest($data);
        $this->stealer->addCache($jett);
        $this->session->set_flashdata('notice', 'Your request was processed. Thanks for joining the movement!');
        $this->load->view('pre');

    }

In the view, pre.php, before the form I have this:
Code:
<p>&lt;?php echo $this->session->flashdata('notice'); ?&gt;</p>

Then after the form, where I have my mention of the last signer:

Code:
<p style="padding-top:12px;">A cheer goes up for our latest signer, &lt;?php foreach ($row as $r) { echo $r->latestu; } ?&gt;!</p>

I don't like running a foreach when I know there is only one bit of data, but I don't know how to pass a query as a single variable rather than an array. So from the model onward I treat the results like an array, even though I'm only after one column in one row.

The companion question is why isn't the flash message displaying? (I am autoloading session) Feel free to put bogus entries in the form today (November 29th). I'll clear out that data tomorrow.

I'd really like to get a grip on this. I'm impressed with CI so far.

#2
[eluser]Michael Wales[/eluser]
Not running through all of your code, just a few tidbits here for you:

The standard method of processing a form goes something like this (assume the user will fail, if they don't send them somewhere else):

Code:
function myForm() {
  if ($this->form_validation->run() !== FALSE) {
    // The user filled out our form correctly, set some flash data
    redirect('success');
  }

  // Here you would add your validation rules and load the view containing the form
  // If we get here the user either has not filled out the form, or did not pass validation
}


And a quick rewrite of your model to prevent the foreach business:
Code:
function getLastSignup() {
  $this->db->order_by('id', 'desc');
  $query = $this->db->get('cache', 1, 0);
  
  if ($query->num_rows() > 0) {
    return $query->row();
  }

  return NULL;
}

#3
[eluser]Leovenous[/eluser]
Michael, thanks for that. Couple things...

There is a form validation function. I left it out because it's working.

On the model, for one thing I'm ditching the 'cache' table and just using the 'interest' table to eliminate redundancy. But I'm still only after the 'fname' column in the most recent row.

I'm still grasping how data is passed around. You gave:
Code:
return $query->row();
How is that passed to the controller and then to the view?

#4
[eluser]Michael Wales[/eluser]
It's passed to the controller thanks to the return statement and would be passed to the view within load->view().

Here's a full MVC example:

Controller
Code:
function index() {
  $this->load->model('user');
  $data['username'] = $this->user->get_username();

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

Model
Code:
function get_username() {
  return 'walesmd';
}

View
Code:
<b>&lt;?php echo $username; ?&gt;</b>

#5
[eluser]Leovenous[/eluser]
[quote author="Michael Wales" date="1291077945"]
View
Code:
<b>&lt;?php echo $username; ?&gt;</b>
[/quote]

Tried that. It's throwing me this:
Code:
A PHP Error was encountered

Severity: 4096

Message: Object of class stdClass could not be converted to string

Filename: views/pre.php

Line Number: 43

Here is where I'm at. The model is autoloaded:

Controller:
Code:
function index()
    {
        $data['fname'] = $this->stealer->getLastSignup();
        $this->load->view('pre', $data);
    }

Model:
Code:
function getLastSignup() {
          $this->db->order_by('id', 'desc');
          $query = $this->db->get('interest', 1, 0);
  
          if ($query->num_rows() > 0) {
            return $query->row();
          }
          return NULL;
    }

View (on line 43):
Code:
&lt;?php echo $fname; ?&gt;

I'm trying to understand, does it not like the type of data in the var?

#6
[eluser]dudeami0[/eluser]
What $query->row() returns is an object that has variables with the column names, so something like:

Code:
$last_signup = $this->stealer->getLastSignup();
$data['fname'] = $last_signup->column_name;

Replacing column_name with whatever your first name column is named.

#7
[eluser]Michael Wales[/eluser]
Because you are returning an object (whereas in my example, I was merely returning a string from my model).

Rather than give you the answer, I'll show you how to figure it out yourself. In your view:

Code:
<pre>
&lt;?php print_r($fname); ?&gt;
</pre>

Take it from there.

#8
[eluser]Leovenous[/eluser]
I'm fine with not getting the outright solution, but don't underestimate my ability to miss the obvious. I tried several things, even went back and reviewed PHP arrays.

I keep coming back to: (I changed the 'fname' in the controller to 'stealer' to reduce confusion)
Code:
&lt;?php echo $stealer['fname']; ?&gt;

Buuuut that doesn't work.

If $stealer is the array that returns:
Code:
stdClass Object ( [id] => 30 [time] => 2010-11-29 11:46:15 [fname] => Marc [email] => [email protected] [zipc] => 12345

Then that means [fname] is the key, right? But if I were right it would work. Welcome to my life.

#9
[eluser]dudeami0[/eluser]
stdClass Object != Array

Code:
&lt;?php echo $stealer->fname; ?&gt;

#10
[eluser]Leovenous[/eluser]
Thanks. I will do more reading on objects. Like I said in my first post, good ole OOP.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.