This tutorial shows you how you can generate JSON from SQL data that comes from model. Converting query to JSON is really simple in PHP and even simpler in CodeIgniter.
You can generate JSON data as string or as seperate file. We convert it to seperate file/url because that is a lot of easyer and it basically makes no difference.
Model:
We need a basic model that gets some data, any data from SQL database is fine actually. It should look something like:Source code viewer
<?php class My_model extends Model { function My_model() { parent::Model(); $this->load->database(); } function get_people() { static $query; $this->db->select('id, name'); $query = $this->db->get('people'); #If you don't want to use acrtive record then you can write your own querys aswell #example: $query = $this->db->query('SELECT id, name FROM people'); if($query->num_rows() > 0) return $query->result(); else return FALSE; } } /* End of file my_model.php */ /* Location: ./system/application/models/my_model.php */Programming Language: PHP
Query to JSON Controller:
I have a json controller. That generates some JSON code to a file/url.Source code viewer
<?php class Json extends Controller { function __construct() { #<-PHP5 - __construct(); PHP4 - class name() parent::Controller(); $this->load->model('my_model'); } function index(){ } } /* End of file json.php */ /* Location: ./system/application/controllers/json.php */Programming Language: PHP
Now you know how to convert query to JSON in CodeIgniter.