Welcome Guest, Not a member yet? Register   Sign In
Getting database to output array
#2

[eluser]vitoco[/eluser]
[quote author="icoder" date="1290839379"]I'm am sure some will figure this out quick as I'm newbie with CI. I need to output from my database what all values I have put into array from my 'books' table. The database is called books as well. The error I receive is You have specified an invalid database connection group. I am sure there are few errors here so please help me out. Thanks!


Controller:
Code:
<?php class Basic extends Controller
{
function Basic()
{
parent::Controller();

}
function fruit()
{
    $this->load->database('books'); //
    $this->load->model('booksmod');
    // CREATE THE DATA ARRAY TO SEND TO THE VIEW
    $data = array();
    // GET THE BOOKS FROM THE MODEL
    $data['books'] = $this->booksmod->connect();
    // LOAD THE VIEW
    $this->load->view('booksview', $data ); // <----- $data as array, not string
}
}


View:
Code:
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Books Data&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
<h1>Results : &lt;?=$books['num_books']?&gt; BOOKS</h1>
    
  

<ul>
&lt;?php foreach($books['lista'] as $book ):?&gt;

<li>
    ISBN : &lt;?=$book['num_books']?&gt; &lt;br&gt;
    TITLE : &lt;?=$book['title']?&gt; &lt;br&gt;
    PRICE : &lt;?=$book['price']?&gt; &lt;br&gt;
    AUTHOR : &lt;?=$book['author']?&gt;
</li>

&lt;?php endforeach;?&gt;
</ul>
    
&lt;/body&gt;
&lt;/html&gt;

Model:
Code:
&lt;?php
class Booksmod extends Model
{
function Booksmod()
{
parent::Model();

}
function connect()
{
    // IT'S VERY USEFUL TO GET THE QUERY INTO A VARIABLE
    // ALSO SPECIFY THE FIELDS INSTEAD IF USE *
    $sql = "
    SELECT
        isbn ,
        price ,
        author ,
        title
    FROM
        books
    ";
    // EXECUTE THE QUERY
    $query = $this->db->query( $sql );    
    // CREATE AN ARRAY TO RETURN THE BOOKS ( ROWS )
    $books = array(
        'num_books' => 0 ,
        'list'      => array() ,
    );

    foreach ($query->result_array() as $row)
    {
        // INCREMENT THE COUNTER OF BOOKS
        $books['num_books']++ ;
        // STORE THE BOOK ( $row )
        $books['list'][] = $row ;
    }

    // CLEAR THE QUERY
    $query->free_result();

    // RETURN THE LIST OF BOOKS
    return $books ;
}
}
[/quote]

Hope it helps you
Saludos

Saludos


Messages In This Thread
Getting database to output array - by El Forum - 11-26-2010, 06:29 PM
Getting database to output array - by El Forum - 11-26-2010, 08:13 PM
Getting database to output array - by El Forum - 11-27-2010, 12:44 AM



Theme © iAndrew 2016 - Forum software by © MyBB