get different result array from model codeigniter - php

I am new in using Codeigniter as web api, I want to get this result
{"result":[{"id":"1","nama":"Orion","nomor":"08576666762"},{"id":"2","nama":"Mars","nomor":"08576666770"},{"id":"7","nama":"Alpha","nomor":"08576666765"}],"success":"1","message":"success"}
but instead I get this kind of result :
{"result":[[{"id":"1","nama":"Orion","nomor":"08576666762"},{"id":"2","nama":"Mars","nomor":"08576666770"},{"id":"7","nama":"Alpha","nomor":"08576666765"}]],"success":"1","message":"success"}
I wonder where am I get it wrong?
I am using codeigniter and my code below is from controller and models
m_server.php (modals)
<?php
Class M_server extends CI_Model {
function __construct(){
parent::__construct();
$this->load->database();
}
// buat view dashboard main
function dash_main1(){
$data = $this->db->query("
select *
from telepon
");
$result = array();
$result['result'] = array();
$result['success'] = "1";
$result['message'] = "success";
array_push($result['result'], $data->result());
return $result;
}
}
Rest_server.php (controller)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Rest_server extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('m_server');
}
public function index()
{
$this->load->helper('url');
$this->load->view('rest_server');
}
function dash_main1(){
$data=$this->m_server->dash_main1();
echo json_encode($data);
}
}

Remove this line (optional)
$result['result'] = array();
And change this line
$result['result'] = $data->result(); //result become the array
array_push add an element to an existing array

Related

Error in codeigniter call to undefined method with my model

I am new in codeigniter, I've read how to load some models with this framework. Now i have a problem regarding with using my model. I have an error of Message: Call to undefined method User_model::select().
My situation is simple, I want to implement a data table and i am using my model by it. Here is what my error comes:
//total records
foreach ($this->user->select("COUNT(*) AS count", $where, $join) as $key => $value) {
$data["iTotalDisplayRecords"] = $value->count;
$data["iTotalRecords"] = $value->count;
}
as you can see, i was using $this->user which is refers to my model i loaded in my constructor:
public function __construct() {
parent::__construct();
if (!$this->ion_auth->logged_in()){
redirect('auth/login', 'refresh');//redirect them to the login page
}
if (!$this->ion_auth->is_admin()){
redirect(base_url().'login', 'refresh');
}else{
$this->admin_id = $this->session->userdata('user_id');
$this->load->library("pagination");
$this->load->model('user_model','user');
}
}
Here is the code of my model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct() {
if ($this->ion_auth->logged_in()){
$this->user_id = $this->session->userdata('user_id');
$group = $this->ion_auth->get_users_groups($this->user_id)->result();
$this->group_id = $group[0]->id;
}
}
public $tbl_name = "users";
}
No this is not the way to call select in CI3. You have to write your own method in the model class then call that method.
I have rewrite your model, try this:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class User_model extends CI_Model
{
private $tbl_name = "users";
public function __construct()
{
if ($this->ion_auth->logged_in()) {
$this->user_id = $this->session->userdata('user_id');
$group = $this->ion_auth->get_users_groups($this->user_id)->result();
$this->group_id = $group[0]->id;
}
}
public function select($select, $where, $join)
{
$this->db->select($select);
$this->db->from($this->$tbl_name);
$this->db->where($where);
$this->db->join($join);
return $this->db->get()->result();
}
}

Dynamic data in codeigniter

I am new in codeigniter and i am working on ecommerce template. By default whenever index() has been hit, it's showing all products in different sections (in html) and I want to make this dynamic so should I use queries in index() for get different type of records or there is any other way? This is my code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
//echo "hello world";
$this->load->view('index');
}
}
?>
First need to create database and table as per your requirement.
Then you can create model for reference check this link : https://www.codeigniter.com/userguide3/general/models.html
<?php
class Blog_model extends CI_Model {
public function get_data_first()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
public function get_data_second()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
}
?>
After making model go to your controller and include it like:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
$this->load->model('my_model');
$data['first_list'] = $this->my_model->get_data_first();
$data['second_list'] = $this->my_model->get_data_second();
//echo "hello world";
$this->load->view('index', $data);
}
}
?>
Then use you param in index file like :
<html>
<head></head>
<body>
<?php
if($first_list){
foreach($first_list as $each){
echo $each->my_param;
}
}
?>
<?php
if($second_list){
foreach($second_list as $each){
echo $each->my_param2;
}
}
?>
</body>
</html>
I hope this helpful for you.
In Models folder write Home_model.php file for querying database.
Suppose you have a table called 'products'.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home_model extends CI_Model{
public function __construct()
{
parent::__construct();
}
public function getProducts()
{
$this->db->from('products');
$query=$this->db->get();
$out = $query->result_array();
return $out;
}
}
The function 'getProducts' will get you all the products from 'products' table.
Now in your controller load the 'database' library and the model.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('home_model');
$this->load->library('database');
}
public function index(){
$products = array();
$products = $this->home_model->getProducts();
$this->load->view('index',$products);
}
}
In index function function of controller you can call the 'getProduct' function of model.And can pass the data to view.
Documentation link for model.
enter link description here
I hope this helps.

CodeIgniter load database in Controller or Model?

Model :
class Users_model extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
public function get_all_users() {
return $this->db->get('users');
}
}
Controller :
class Users extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Users_model');
}
public function index() {
redirect('users/view_users');
}
public function view_users() {
$data['query'] = $this->Users_model->get_all_users();
$this->load->view('users/view_all_users', $data);
}
}
My question is where should i put the $this->load->database? In Model or Constructor? If possible tell me why?
And one more question, if i omit the $this->load->database, the error shown
"Undefined property: Users::$db". I'm expecting "Undefined property:
Users_model::$db".
Why is that? Is it looking for $db in both controller or model?
Thank you.
Note: i can connect to database just fine. What im actually ask is if i want to use $this->load->database(). Where should i put it? Controller or Model? And why?
You can either load the database in the controller or you can load it in the model.There's not much of a difference its just more neat and clean that all the interaction in the database is in the model and the controllers the one who connects both views and model.The controller here is like a middleman between the buyer and the seller.
load database in the controller
<?php
class Test_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database('default');
$this->load->model('test_model');
}
public function index()
{
$this->db->from('test');
$query = $this->db->get();
echo "<title>CodeIgniter SQlite</title>";
$data['db']=$query->result();
//print_r($data['db']);
$count = count($data['db']);
echo "Row count: $count rows<br>";
for ($i=0; $i < $count; $i++) {
echo $data['db'][$i]->text." ";
}
}
}
?>
load database in the model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test_model extends CI_Model
{
public $table1 = 'test';
public $table2 = '';
public function __construct()
{
parent::__construct();
$this->load->database('default');
}
public function check_db()
{
$this->db->from($this->table1);
$query = $this->db->get();
return $query->result();
}
}
Go to autoload.php in application/config/autoload.php and add this
$autoload['libraries'] = array('database'); // add database in array(now you dont need to load database at anywhere in project)
Make database connection settings in database.php, file located atapplication/config/database.php
now try this
class Users_model extends CI_Model {
function __construct() {
parent::__construct();
//$this->load->database(); <----remove this
}
public function get_all_users() {
return $this->db->get('users');
}
}

Passing common title to all view and models CodeIgniter

I have this controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('text');
}
public function index()
{
$this->home();
}
public function home()
{
$data['title']="Somesite";
$this->load->view("view_home", $data);
}
public function blog()
{
$data['title']="Somesite";
$this->load->view("view_blog", $data);
}
public function answers()
{
$data['title']="Somesite";
$this->load->view("view_answers", $data);
}
}
As you may see $data['title'] is same for all functions, how to make it simpler, to include at the beggining and not to write it in every function, repeat again, and then transfer to view.
Is there a way to tranfer it to function?
Before construct function add this:
public $data = array();
Then in the construct function write:
$this->data['title']="Somesite";
And finally before load view add this:
$data = $this->data + $data;
Now you have same $title everywhere.
Here si simple solution and elegant for transfering one variable to all views :)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller {
//Class-wide variable to store stats line
protected $title;
function __construct()
{
parent::__construct();
$data->title = "Some site";
$this->load->vars($data);
}
I'm using this method in every projects.
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
//Global variable
public $outputData = array();
public $loggedInUser;
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->helper('url');
$this->load->view('users/users');
}
public function register() {
parent::__construct();
$this->load->helper('url');
$this->load->model('users_model');
//get country names
$countryList = $this->users_model->getCountries();
$this->outputData['countryList'] = $countryList;
$this->outputData['pageTitle'] = "User Registration";
$this->load->view('users/register',$this->outputData);
}
}
View file
<?php if(isset($pageTitle)) echo $pageTitle; ?>
<?php
if(isset($countryList)){
print_r($countryList);
}
?>

CodeIgniter: Passing Arguments from View to Controller?

EDIT: With the code below now, I am unsure on how to print out the bookmarks and the tags correctly
I’m completely new to CI and I have recently hit a road block. I’m very unsure how I would go about passing a function argument from the view file to the controller so I could use it on a function?
I have a foreach loop on the view going through the all the items passed by function get_latest_bookmarks. That function returns a ID for each item and I am wanting to use this with another function called get_bookmark_tags which will get the tags of the bookmark from another table. I have provided the code I have done so far below.
Model:
<?php
class Bookmark_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_latest_bookmarks($limit)
{
// Load Database
$this->load->database();
// Query Database
$query = $this->db->get('Bookmark', $limit);
// Return Result
return $query;
}
function get_bookmark_tags($id)
{
// Load Database
$this->load->database();
$query = $this->db->query('SELECT Tag.Title
FROM `Tag`
INNER JOIN BookmarkTag
WHERE BookmarkTag.BookmarkID = "'.$id.'" AND Tag.TagID = BookmarkTag.TagID');
return $query;
}
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
// Load URL Helper
$this->load->helper('url');
// Load User Library
$this->load->library('ion_auth');
// Is User Logged In
if ($this->ion_auth->logged_in())
{
$data['user'] = $this->ion_auth->get_user_array();
}
else
{
redirect('auth/login');
}
// Load Bookmark Model
$this->load->model('Bookmark_model');
// Create Arrays
$bookmarks = array();
$tags = array();
// Query Database
$query = $this->Bookmark_model->get_latest_bookmarks(4);
//
foreach ($query->result() as $row) {
array_push($tags, $this->Bookmark_model->get_bookmark_tags($row->BookmarkID));
array_push($bookmarks, $row);
}
$data['tags_latest'] = $tags;
$data['bookmarks_latest'] = $bookmarks;
$this->load->view('welcome_message', $data);
}
}
View:
<h1>Latest Bookmarks</h1>
<?php foreach ($bookmarks_latest as $bookmark): ?>
<?php print_r($bookmark); ?>
<?php print_r($tags_latest->result()); ?>
<?php endforeach; ?>
You should do that in your Controller before you are passing the data to the View.
Try with something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
// Load Model
$this->load->model('Bookmarks');
// Get Latest Bookmarks
$query = $this->Bookmarks->get_latest_bookmarks(4);
$bookmarks = array();
$tags = array();
foreach ($query->result() as $row) {
$bookmark_query = $this->Bookmarks->get_bookmark_tags($row->id);
$bookmark_arr = array();
foreach (bookmark_query->result() as $bookm) {
array_push($bookmark_arr, $bookm);
}
array_push($tags, $bookmark_arr);
array_push($bookmarks, $row);
}
$data['tags'] = $tags;
$data['bookmarks'] = $bookmarks;
// Load and Pass Data into View
$this->load->view('welcome_message', $data);
}
}
You don't.
The point in using a Framework is to default to proper standards. CodeIgniter follows a loose MVC pattern but you should never pass things from the view to the controller.
You can do it, but if you do it you'll be getting into a spaghetti mess pretty soon.
Grab the ID's on the controller. Even if it implicates running the same loop twice. You'll thank yourself latter on.

Categories