CodeIgniter Forums

Full Version: CodeIgniter Tutorial News section
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I am now studying the News section - user_guide\tutorial\news_section.html - and having to spend many hours trying to understand, and where I expect I should be spending only around an hour on such simple instructions.


(1) The 1st is clear. - Open up the application/models directory and create a new file called News_model.php and add the following code.
(2) The 2nd is difficult to understand. - Connect to your database and run the SQL command below. Also add some seed records. - How do I connect to the database and how do I run the SQL command? I assume the command is to be pasted into News_model.php
(3) The 3rd is partially clear. - Add the following code to your model. - I assume the code is to be pasted into News_model.php
(4) The 4th is partially clear. - Create the new controller at application/controllers/News.php. - I assume the code is to be pasted into News.php
(5) The 5th is difficult to understand. - The next thing to do is passing this data to the views. - I assume the code is to be pasted into News.php
(6) The 6th is clear. - Create application/views/news/index.php and add the next piece of code.
(7) The 7th is difficult to understand. - Go back to the news controller and update view() with the following: - I assume the code is to be pasted into News.php but don't understand why there are 2 loads.
(8) The 8th is clear. - The only things left to do is create the corresponding view at application/views/news/view.php. Put the following code in this file.
(9) The 9th is clear. - Modify your routing file (application/config/routes.php) so it looks as follows.

After following those instructions and assumptions, and pointing my browser to http://localhost/MyProject/index.php/news I can only get an error page - The website cannot display the page - HTTP 500

This is the code in my News_model.php page

Code:
<?php
class News_model extends CI_Model
{

       public function __construct()
       {
               $this->load->database();
       }

       CREATE TABLE news (
       id int(11) NOT NULL AUTO_INCREMENT,
       title varchar(128) NOT NULL,
       slug varchar(128) NOT NULL,
       text text NOT NULL,
       PRIMARY KEY (id),
       KEY slug (slug)
);

public function get_news($slug = FALSE)
{
       if ($slug === FALSE)
       {
               $query = $this->db->get('news');
               return $query->result_array();
       }

       $query = $this->db->get_where('news', array('slug' => $slug));
       return $query->row_array();
}
}
This is the code in my News.php page
Code:
<?php
class News extends CI_Controller
{
       public function __construct()
       {
               parent::__construct();
               $this->load->model('news_model');
       }

       public function index()
       {
               $data['news'] = $this->news_model->get_news();
       }

       public function view($slug = NULL)
       {
               $data['news_item'] = $this->news_model->get_news($slug);
       }

       public function index()
       {
       $data['news'] = $this->news_model->get_news();
       $data['title'] = 'News archive';

       $this->load->view('templates/header', $data);
       $this->load->view('news/index', $data);
       $this->load->view('templates/footer');
       }

       public function view($slug = NULL)
       {
       $data['news_item'] = $this->news_model->get_news($slug);

       if (empty($data['news_item']))
       {
               show_404();
       }

       $data['title'] = $data['news_item']['title'];

       $this->load->view('templates/header', $data);
       $this->load->view('news/view', $data);
       $this->load->view('templates/footer');
       }
}

I have tried many variations, and now exhausted, and need guidance. Can anybody help?
Step 2) SQL commands are run using a SQL tool, for instance phpmyadmin. They do not belong in your code (model or otherwise), as they are not PHP.

Step 7) Each of the "loads" renders a fragment of the result page

Hope this helps
(07-27-2015, 09:00 AM)christaliise Wrote: [ -> ]I am now studying the News section - user_guide\tutorial\news_section.html - and having to spend many hours trying to understand, and where I expect I should be spending only around an hour on such simple instructions.


(1) The 1st is clear. - Open up the application/models directory and create a new file called News_model.php and add the following code.
(2) The 2nd is difficult to understand. - Connect to your database and run the SQL command below. Also add some seed records. - How do I connect to the database and how do I run the SQL command? I assume the command is to be pasted into News_model.php
(3) The 3rd is partially clear. - Add the following code to your model. - I assume the code is to be pasted into News_model.php
(4) The 4th is partially clear. - Create the new controller at application/controllers/News.php. - I assume the code is to be pasted into News.php
(5) The 5th is difficult to understand. - The next thing to do is passing this data to the views. - I assume the code is to be pasted into News.php
(6) The 6th is clear. - Create application/views/news/index.php and add the next piece of code.
(7) The 7th is difficult to understand. - Go back to the news controller and update view() with the following: - I assume the code is to be pasted into News.php but don't understand why there are 2 loads.
(8) The 8th is clear. - The only things left to do is create the corresponding view at application/views/news/view.php. Put the following code in this file.
(9) The 9th is clear. - Modify your routing file (application/config/routes.php) so it looks as follows.

After following those instructions and assumptions, and pointing my browser to http://localhost/MyProject/index.php/news I can only get an error page - The website cannot display the page - HTTP 500

This is the code in my News_model.php page


Code:
<?php
class News_model extends CI_Model
{

       public function __construct()
       {
               $this->load->database();
       }

       CREATE TABLE news (
       id int(11) NOT NULL AUTO_INCREMENT,
       title varchar(128) NOT NULL,
       slug varchar(128) NOT NULL,
       text text NOT NULL,
       PRIMARY KEY (id),
       KEY slug (slug)
);

public function get_news($slug = FALSE)
{
       if ($slug === FALSE)
       {
               $query = $this->db->get('news');
               return $query->result_array();
       }

       $query = $this->db->get_where('news', array('slug' => $slug));
       return $query->row_array();
}
}
This is the code in my News.php page

Code:
<?php
class News extends CI_Controller
{
       public function __construct()
       {
               parent::__construct();
               $this->load->model('news_model');
       }

       public function index()
       {
               $data['news'] = $this->news_model->get_news();
       }

       public function view($slug = NULL)
       {
               $data['news_item'] = $this->news_model->get_news($slug);
       }

       public function index()
       {
       $data['news'] = $this->news_model->get_news();
       $data['title'] = 'News archive';

       $this->load->view('templates/header', $data);
       $this->load->view('news/index', $data);
       $this->load->view('templates/footer');
       }

       public function view($slug = NULL)
       {
       $data['news_item'] = $this->news_model->get_news($slug);

       if (empty($data['news_item']))
       {
               show_404();
       }

       $data['title'] = $data['news_item']['title'];

       $this->load->view('templates/header', $data);
       $this->load->view('news/view', $data);
       $this->load->view('templates/footer');
       }
}

I have tried many variations, and now exhausted, and need guidance. Can anybody help?


Do you know to code in plain PHP ?
Do you know what is PHP or MySQL or a SQL command?

If you donțt know, than you should learn them first and after a year or two, give a try to CodeIgniter.
(07-27-2015, 09:48 AM)ciadmin Wrote: [ -> ]Step 2) SQL commands are run using a SQL tool, for instance phpmyadmin. They do not belong in your code (model or otherwise), as they are not PHP.

Step 7) Each of the "loads" renders a fragment of the result page

Hope this helps

Thanks ciadmin. I have read Connecting to your Database - Automatically Connecting. As CodeIgniter is doing most other things automatically, I would like to learn (and I guess most other students of CodeIgniter) the code so that my project can automatically connect to the database. I have already changed application/config/autoload.php to

Code:
$autoload['libraries'] = array('database', 'email', 'session');

but I guess there will be significant coding for it to happen.
Inside the application/config folder you will find a file named "database.php".
Modify this file according to the correct database settings.
Once you've done that, calling the database library [ with $this->load->library('database') ] will establish the right connection.
To run sql commands, you do this:
PHP Code:
$this->db->query("SELECT * FROM ..."); 

And that's just one of the many methods in the database library. Studying the documentation about running database queries can help you a lot.

Important! If you are planning to use a local database for your development environment, and another database for your production environment, make two versions of database.php. One in application/config/development, the other in application/config/production.
CI will use the correct file, depending on the environment setting in your index.php file.
(07-28-2015, 02:30 AM)Wouter60 Wrote: [ -> ]Inside the application/config folder you will find a file named "database.php".
Modify this file according to the correct database settings.
Once you've done that, calling the database library [ with $this->load->library('database') ] will establish the right connection.
To run sql commands, you do this:

PHP Code:
$this->db->query("SELECT * FROM ..."); 

And that's just one of the many methods in the database library. Studying the documentation about running database queries can help you a lot.

Important! If you are planning to use a local database for your development environment, and another database for your production environment, make two versions of database.php. One in application/config/development, the other in application/config/production.
CI will use the correct file, depending on the environment setting in your index.php file.

Thanks Wouter60. I have already created a database and configured "database.php" and modified "autoload.php" to $autoload['libraries'] = array('database', 'email', 'session');

I like to learn how to create the table automatically using PHP and in accordance with the Tutorial. Undoubtedly when the table is created the Tutorial will explain the query process.

I'm intending to build only one project and doubt if I'll need development and production environments.
Like @ciadmin suggested, the best way is to create the table with the database tool you are using, because this is just a one-time issue.
If you managed to create a database, that means that you have access to phpmyadmin. Open it and select your database. Click the SQL tab and paste the sql-command that you find in the CI documentation. Click Start to run the command. The news table is created.
After you've done that, insert a few records. Use your fantasy to make up a few titles, and search the internet for lorum ipsum texts that can be used as imaginary news items.
Once these records exist, you can use CI to collect records from the database and pass data to your views.
(07-28-2015, 08:15 AM)christaliise Wrote: [ -> ]I like to learn how to create the table automatically using PHP and in accordance with the Tutorial. Undoubtedly when the table is created the Tutorial will explain the query process.

The database forge library allows you to modify/create/drop tables.
http://www.codeigniter.com/user_guide/da...forge.html

It also helps to know the database library's metadata methods for things like finding out if a table exists before you create it:
http://www.codeigniter.com/user_guide/da...adata.html

So, for example, you might do something like this:
PHP Code:
if ( ! $this->db->table_exists('table_name')) {
    $fields = array(
        'id' => array(
            'type' => 'int',
            'constraint' => 11,
            'auto_increment' => true,
        ),
        'title' => array(
             'type' => 'varchar',
             'constraint' => 255,
             'null' => false,
        ),
    );
    
    $this
->load->dbforge();
    $this->dbforge->add_field($fields);
    $this->dbforge->add_key('id'true);
    $this->dbforge->create_table('table_name');
}

// Now your table should be ready 

Note that you would normally do something like this in a migration, so you can add/remove the table as needed using the migration library.
Quote:(5) The 5th is difficult to understand. - The next thing to do is passing this data to the views. - I assume the code is to be pasted into News.php

You're right: the index() method is part of the News controller.
It collects the news items via the model.
It stores the data in an array called $data.

Then, it passes this array to the views that are loaded:
PHP Code:
$this->load->view('news/index'$data); 

The first parameter for loading the view is the view file itself. In this case application/views/news/index.php.
The second parameter is an array containing all the variables that you want to pass to the view. In this case $data.

The view will automatically extract the array. So, when your controller defines an array element $data['news'], the view can simply process a variable $news. Which - in this case - is an array itself, containing one or more records. That's why the view index.php has a foreach .... endforeach loop to display the text from all news items.
Are you getting the picture?
(07-29-2015, 12:31 PM)mwhitney Wrote: [ -> ]
(07-28-2015, 08:15 AM)christaliise Wrote: [ -> ]I like to learn how to create the table automatically using PHP and in accordance with the Tutorial. Undoubtedly when the table is created the Tutorial will explain the query process.

The database forge library allows you to modify/create/drop tables.
http://www.codeigniter.com/user_guide/da...forge.html

It also helps to know the database library's metadata methods for things like finding out if a table exists before you create it:
http://www.codeigniter.com/user_guide/da...adata.html

So, for example, you might do something like this:

PHP Code:
if ( ! $this->db->table_exists('table_name')) {
    $fields = array(
        'id' => array(
            'type' => 'int',
            'constraint' => 11,
            'auto_increment' => true,
        ),
        'title' => array(
             'type' => 'varchar',
             'constraint' => 255,
             'null' => false,
        ),
    );
    
    $this
->load->dbforge();
    $this->dbforge->add_field($fields);
    $this->dbforge->add_key('id'true);
    $this->dbforge->create_table('table_name');
}

// Now your table should be ready 

Note that you would normally do something like this in a migration, so you can add/remove the table as needed using the migration library.

Thanks mwhitney I'm grateful for your help.
Pages: 1 2