CodeIgniter Forums
Echoing results from a database - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Echoing results from a database (/showthread.php?tid=16581)

Pages: 1 2 3


Echoing results from a database - El Forum - 03-10-2009

[eluser]mdcode[/eluser]
I apologize if this is a really dumb question but I've gone through some tutorials and looked at the documentation, even read some threads detialing this on these forums but I just can't figure out where I am going wrong, and think I just need some specific help.

I have a couple of tables which hold items like the site title, admin email, a welcome message etc. I have made up the controller, the model, and the view to pull those results and display them to the user, and all I get is the following error message in a big red box:
Code:
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Filename: views/home_view.php
Line Number: 11

My controller is coded like this:
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
System Version: 1.0
**/

class Home extends Controller {

    function __construct()
    {
        parent::Controller();    
    }
    
    function index()
    {
        $this->load->model('home_model');
        $data['siteTitle'] = $this->home_model->get_settings();
        $data['intro'] = $this->home_model->get_messages();
        $this->load->view('home_view', $data);
    }
}

/* End of file */
/* Location: controllers/home.php */

My model is constructed thusly:
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
System Version: 1.0
**/

class home_model extends Model {

    function __construct()
    {
        parent::Model();
    }
    
    function get_settings()
    {
    $this->db->select('siteTitle');
    $setquery = $this->db->get('settings');
    return $setquery;
    }
        
    function get_messages()
    {
    $this->db->select('intro');
    $msgquery = $this->db->get('messages');
    return $msgquery;
    }
    
}

/* End of file */
/* Location: models/home_model.php */

And my view looks like this:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
&lt;html &gt;

&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;title&gt;&lt;?php echo $siteTitle; ?&gt;&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

<span class="fontTitle">Welcome to the &lt;?php echo $siteTitle; ?&gt;</span>
<br(2)>
<span class="fontNormal">&lt;?php echo $intro; ?&gt;</span>

&lt;/body&gt;

&lt;/html&gt;

And so I come to you guys -- I have been going on this for almost two days, looking at the documentation, reading tutorials, and virtually blindly mashing a code and I cannot see where I have gone wrong. Hoping someone can help me out here -- and freshly-baked cookies will go out to the person that does...


PS. Line 11 is the first echo statement 'Welcome to the title_of_the_site'


Echoing results from a database - El Forum - 03-10-2009

[eluser]Thorpe Obazee[/eluser]
http://ellislab.com/codeigniter/user-guide/database/results.html

Code:
$query = $this->db->query("YOUR QUERY");

foreach ($query->result() as $row)
{
   echo $row->title;
   echo $row->name;
   echo $row->body;
}

You should return the query result first then loop through it and then that's when you echo.


Echoing results from a database - El Forum - 03-11-2009

[eluser]mdcode[/eluser]
Wow... thanks for the quick response, though I'm probably being a dunce on this, but I have put this in home_model, tested the page and while the information is "echoed", it is in the wrong place, so I have "the_site_title Welcome to the"...

Also, there is only one row in each of the settings and messages tables, so returning it in this way seems wrong to me.

In addition, I get a new error message:
Code:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$siteTitle
Filename: models/home_model.php
Line Number: 41
Line 41 of home_model.php is:
Code:
echo $row->siteTitle;

Any more light over here...??


Echoing results from a database - El Forum - 03-11-2009

[eluser]TheFuzzy0ne[/eluser]
That's usually a sign that you didn't get a result, or that the field name you're calling upon doesn't exist. I'd suggest you test for a result first using:
Code:
if ($query->num_rows())
{
    # Do whatever
}



Echoing results from a database - El Forum - 03-11-2009

[eluser]mdcode[/eluser]
Ok, yep, I was being partly silly, since the siteTitle field is not in the messages table and I had just copied and pasted code, changed most of it bar that and now I have the two items querying normally. However, I am now just left with the original error:

Code:
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Filename: views/home_view.php
Line Number: 11

Along with the fact that "Welcome to the" is being echoed at the end of the echoed statements being pulled from the database.


Echoing results from a database - El Forum - 03-11-2009

[eluser]TheFuzzy0ne[/eluser]
You're trying to print the result object itself again. Please post you controller and view code.


Echoing results from a database - El Forum - 03-11-2009

[eluser]mdcode[/eluser]
Nothing has changed bar what's already been suggested... but here's a refresher:

Controller:
Code:
class Home extends Controller {

    function __construct()
    {
        parent::Controller();    
    }
    
    function index()
    {
        $this->load->model('home_model');
        $data['siteTitle'] = $this->home_model->get_settings();
        $data['intro'] = $this->home_model->get_messages();
        $this->load->view('home_view', $data);
    }
}

/* End of file */
/* Location: controllers/home.php */

View:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
&lt;html &gt;

&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;title&gt;&lt;?php echo $siteTitle; ?&gt;&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

<span class="fontTitle">Welcome to the &lt;?php echo $siteTitle; ?&gt;</span>
<span class="fontNormal">&lt;?php echo $intro; ?&gt;</span>

&lt;/body&gt;

&lt;/html&gt;

And the modified model using previous suggestions (just in case it's relevant):
Code:
class home_model extends Model {

    function __construct()
    {
        parent::Model();
    }
    
    function get_settings()
    {
    $this->db->select('siteTitle');
    $setquery = $this->db->get('settings');
        foreach ($setquery->result() as $row)
        {
           echo $row->siteTitle;
        }
    return $setquery;
    }
        
    function get_messages()
    {
    $this->db->select('intro');
    $msgquery = $this->db->get('messages');
        foreach ($msgquery->result() as $row)
        {
           echo $row->intro;
        }
    return $msgquery;
    }
    
}

/* End of file */
/* Location: models/home_model.php */



Echoing results from a database - El Forum - 03-11-2009

[eluser]TheFuzzy0ne[/eluser]
You're model is a bit strange.
Code:
class home_model extends Model {

    function __construct()
    {
        parent::Model();
    }
    
    function get_settings()
    {
    $this->db->select('siteTitle');
    $setquery = $this->db->get('settings');
        foreach ($setquery->result() as $row)
        {
           echo $row->siteTitle; // No idea what this is all about.
        }
    return $setquery; // You're still returning the result object.
    }
        
    function get_messages()
    {
    $this->db->select('intro');
    $msgquery = $this->db->get('messages');
        foreach ($msgquery->result() as $row)
        {
           echo $row->intro; // No idea what this is all about
        }
    return $msgquery; // Your still returning the result object
    }
    
}

/* End of file */
/* Location: models/home_model.php */

Here's my suggested replacement:
Code:
class home_model extends Model {

    function __construct()
    {
        parent::Model();
    }
    
    function get_settings()
    {
        $this->db->select('siteTitle');
        $res = $this->db->get('settings');
        if ($res->num_rows())
        {
            $res = $setquery->row();
            return $res->siteTitle;
        }

        return $setquery->siteTitle;
    }
        
    function get_messages()
    {
        $this->db->select('intro');
        $res = $this->db->get('messages');

        if ($res->num_rows())
        {
            $res = $res->row();
            return $res->intro;
        }
        return FALSE;
    }
    
}

/* End of file */
/* Location: models/home_model.php */
The above code is untested.

However, I'm concerned that your database table is not efficiently designed. I get the impression that each setting has it's own column, when really, a settings table should look a bit like this:

Code:
+------------+---------+
| key        | value   |
+------------+---------+
| site_title | My Site |
| setting 1  | value   |
| setting 2  | value   |
|            |         |
Then you can select the key(s) you need using a WHERE clause.


Echoing results from a database - El Forum - 03-11-2009

[eluser]mdcode[/eluser]
No worries about the untested part, mate, I'm just glad for the help -- it's nice to find a forum that has good, friendly, helpful people on it (and I've been on my share of forums). But with a slight error where you didn't change out all the references to "$setquery", I changed to "$res" and voila! I now have both results, displaying in the correct order, with no errors to speak of, thank you very much, sir...

Freshly baked cookies winging their way to you.


Just in case you are interested, the tables are designed like this:

settings:
Code:
id - siteTitle     - adminEmail
1  - Such and such - me@work

And messages is set up much the same, only 1 row will ever exit in these tables.

Thanks again -- on with the next question...


Echoing results from a database - El Forum - 03-11-2009

[eluser]TheFuzzy0ne[/eluser]
I'm glad I could help. Mmmm, cookies! Big Grin

If you only require a single database row, I'd suggest using a config file instead (so long as you don't need to dynamically update it). If you do, there's another method, which is simply to serialize a configuration array, and dump it into a file. Load the file and unserialize it to work with the data. The purpose of a database (besides storing data) is to index that data so you can search quickly. In your case, no searching is necessary. If you store the settings in the config.php, you have the added bonus of saving yourself quite a few database queries.

Oh, and welcome to the CodeIgniter forums! Smile