How to load all rows in codeigniter-base-model? REST api - php

I am trying to load all rows for my REST API through Postman.
I am using codeigniter-base-model MY_Model.php.
https://github.com/jamierumbelow/codeigniter-base-model
This is how my code currently looks like both in my controller/model:
Controller(api_news.php):
class Api_News extends REST_Controller {
function __construct()
{
parent::__construct();
}
function index_get()
{
$id = $this->uri->segment(3);
$this->load->model('News_model');
$news = $this->News_model->get_by(array('id' => $id));
if(isset($news['id'])) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
}
Model(news_model.php):
class News_model extends MY_Model{
protected $_table = 'news';
protected $primary_key = 'id';
protected $return_type = 'array';
}
At the moment if I access:
localhost/my_api/api_news/id/1, 2, 3, etc...
I can access any record by its individual ID and it shows up which is great.
BUT I also want to be able to see all rows by doing this:
localhost/my_api/api_news/id/
and have all rows showing at once.
But I am not sure how to do this...and am getting an unsuccess/false if I try.
Can you please show me how? I am new to PHP in general and I appreciate any help.
Thank you so much!!

Make some changes in your Controller function as below -
function index_get(){
$id = $this->uri->segment(3);
$this->load->model('News_model');
// pass $id to model
$news = $this->News_model->get_by( $id );
if( !empty( $news ) ) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
And in your model make id parameter optional and then check that if id is passed get data based on id otherwise return all data as below -
// $id variable is optional here
function get_by( $id = '' ) {
if ( $id == '' ) {
$news = $this->db->get( 'news' );
}
else {
$news = $this->db->get_where( 'news', array( 'id' => $id ) );
}
// return data to controller
return $news->result();
}
So if you enter id in API then data will be based on that id otherwise all data will be returned.

Related

localhost send an invalid response code igniter 4

I'm just learning CI4 from Youtube "web programming unpas" on episode 9 insert data (its using indonesia language). Well I followed the course and tried to insert data. After insert data to database, it will be redirected to the index file.
So the error is showing localhost send an invalid response
Idk what's the problem
Here is the code
routes.php
$routes->get('/', 'pages::index');
$routes->get('/komik/create', 'komik::create');
$routes->get('/komik/(:segment)', 'komik::detail/$1');
controller/komik.php
<?php
namespace App\Controllers;
use App\Models\komikmodel;
class komik extends BaseController
{
protected $komikmodel;
public function __construct()
{
$this->komikmodel = new komikmodel();
}
public function index()
{
$data = [
'title' => 'Daftar Komik' ,
'komik' => $this->komikmodel->getkomik()
];
return view('komik/index', $data);
}
public function detail($slug)
{
$data = [
'title' => 'Detail Komik',
'komik' => $this->komikmodel->getkomik($slug)
];
if(empty($data['komik']))
{
throw new \CodeIgniter\Exceptions\PageNotFoundException('Judul Komik '. $slug. 'Tidak Ditemukan');
}
return view('komik/detail', $data);
}
public function create()
{
$data = [
'title' => 'Form Tambah Data Komik'
];
return view('/komik/create', $data);
}
public function save()
{
$slug = url_title($this->request->getVar('judul'), '-', true);
$this->komikmodel->save([
'judul' => $this->request->getVar('judul'),
'slug' => $slug,
'penulis' => $this->request->getVar('penulis'),
'penerbit' => $this->request->getVar('penerbit'),
'sampul' => $this->request->getVar('sampul')
]);
session()->setFlashData('pesan', 'Data berhasil di tambahkan!');
return redirect()->to('/komik');
}
}
Any advice will be appreciated

last inserted id in Php codeIgniter

In my model I have return below function for get record id
function getLastInserted()
{
$query = $this->db->select("MAX(`UserID`)+1 as userid")->get("registeration");
return $query->result();
}
Now I want to pass that ID to mycontroller for record insertion
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
Now I want to access model function in controller and pass record id in data function How I do ??
set return in model and in controller write
$insert_id=$this->db->insert_id();
In Controller load your model first using
$this->load->model('model_name');
Then call to model's getLastInserted() function.
$ID = $this->model_name->getLastInserted();//you will get id here
In model return $query->row()->userid; insead return of $query->result().
Then modify the controller:
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $this->model_name->getLastInserted(),
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
hi i worked out the solution on last inserted id dear here the code:
controller:
function sample() {
$sid=$this->adminmodel->getLastInserted();
$this->adminmodel->newregistration( $sid);
}
model:
function getLastInserted()
{
$query = $query = $this->db->select('id')->order_by('id','desc')->limit(1)->get('employee_outs')->row('id');
return $query;
}
model:
public function newregistration($sid)
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $sid,
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}

call_user_func_array() expects parameter 1 to be a valid callback, no array or string given Kohana 3.3.4

Hey guys i have read and studied the kohana orm and auth modules. so i want to implement am admin section to my website. i get the error above and i have googled but can't seem to find the answer. am using Kohana 3.3.4
so a created a controller called admin:
<?php defined('SYSPATH') or die('No direct script access!');
class Controller_Admin extends Controller_Dev
{
public $template = 'login_template';
public function action_index()
{
if (Auth::instance()->logged_in()) {
$this->redirect->body('admin/dashboard', 302);
}
$this->redirect('admin/login');
}
//lets login user
public function action_login()
{
$view = new View('admin_login');
$this->template->title = "Log in";
if ($_POST) {
$user = ORM::factory('user');
$status = $user->login($_POST);
if ($status) {
$this->redirect('admin/dashboard', 302);
}
else {
$errors = $_POST->errors('admin/login');
}
}
// Display the login form
$this->template->content = $view;
}
//lets logout user
public function action_logout()
{
Auth::instance()->logout();
$this->redirect('admin/login', 302);
}
//lets register new users
public function action_register()
{
$view = View::factory('admin_register')
->set('values', $_POST)
->bind('errors', $errors);
$this->template->title = "Registration Page";
if ($_POST)
{
$user = ORM::factory('User');
// The ORM::values() method is a shortcut to assign many values at once
/* $external_values = array(
// The unhashed password is needed for comparing to the password_confirm field
'password' => Arr::get($_POST, 'password'),
// Add all external values
) + Arr::get($_POST, '_external', array());
$extra = Validation::factory($external_values)
->rule('confirm_password', 'matches', array(':validation', ':field', 'password')); */
try
{
//$test = $extra; //Arr::get($_POST, 'password');
//$view->test = $test;
$data = $this->request->post();
$user->register($data);
// Redirect the user to his page
$this->redirect('admin/login');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors('models');
}
}
$this->template->content = $view;
}
and i created a model called user to help me validate the new user account before save it to the database:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_User extends Model_Auth_User {
//public $_table_name = 'users';
protected $_has_many = array(
'user_tokens' => array('model' => 'user_token'),
'roles' => array('model' => 'role', 'through', 'roles_users'),
// for facbook, google+, twitter and yahoo indentities
'user_identity' => array(),
);
protected $_ignored_columns = array('confirm_password');
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 32)),
array(array($this, 'username_available')),
),
'password' => array(
'not_empty' => NULL,
'min_length' => array(5),
'max_length' => array(42),
),
'password_confirm' => array(
'matches' => array('password'),
),
'email' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(127),
'email' => NULL,
),
);
}
public function filters()
{
return array(
'password' => array(
array(array($this, 'hash_password')),
),
);
}
public function username_available($username)
{
// There are simpler ways to do this, but I will use ORM for the sake of the example
//return ORM::factory('Member', array('username' => $username))->loaded();
// Check if the username already exists in the database
return ! DB::select(array(DB::expr('COUNT(username)'), 'total'))
->from('users')
->where('username', '=', $username)
->execute()
->get('total');
}
public function hash_password($password)
{
// Do something to hash the password
}
public function register($array)
{
$this->values($array);
$this->save();
// Create a new user record in the database
// Save the new user id to a cookie
cookie::set('user', $id);
return $id;
}
}
When i visit the admin registration page. it fails displaying an error which says:
ErrorException [ Warning ]: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given
so please help me out because i think i might be missing something. Thanks in advance guys. Am using Kohana 3.3.4
I had the same error recently. You need to change line:
array(array($this, 'username_available')),
to line (for username):
array(array($this, 'unique'), array('username', ':value')),
as stated in https://kohanaframework.org/3.3/guide-api/Model_Auth_User#rules
I hope this helps you.

How to insert multiple data using insert_batch in codeigniter

Here i am getting inserted data to database but how to write this in foreach loop to get multiple data please help me as a fresher am totally confused..
My controller
class Student extends CI_Controller {
public function _construct()
{
parent::_construct();
//call model
$this->load->model("StudentModel","m");
}
function index()
{
$this->load->view("index");
}
function savedata()
{
//create array for get data from index
//$data=array(
// 'studentname' => $this->input->post('studentname'),
//'gender' => $this->input->post('gender'),
//'phone' => $this->input->post('phone')
// );
$data = array(
array(
'studentname' => 'Reddy' ,
'gender' => 'Male' ,
'phone' => '456879'
),
array(
'studentname' => 'Yalla' ,
'gender' => 'Female' ,
'phone' => '12345678'
)
);
//mean that insert into database table name tblstudent
$this->db->insert_batch('tblstudent',$data);
//mean that when insert already it will go to page index
redirect("Student/index");
}
function edit($id)
{
$row=$this->m->getonerow($id);
$data['r']=$row;
$this->load->view('edit',$data);
}
function update($id)
{
$id=$this->input->post('id');
$data=array(
'studentname' => $this->input->post('studentname'),
'gender' => $this->input->post('gender'),
'phone' => $this->input->post('phone')
);
$this->db->where('id',$id);
$this->db->update('tblstudent',$data);
redirect("Student/index");
}
function delete($id)
{
$id=$this->db->where('id',$id);
$this->db->delete('tblstudent');
redirect("Student/index");
}
}
My model
class StudentModel extends CI_Model{
function _construct()
{
parent::_construct();
}
function gettable()
{
$query=$this->db->get('tblstudent');
return $query->result();
}
function getonerow($id)
{
$this->db->where('id',$id);
$query = $this->db->get('tblstudent');
return $query->row();
}
}
For CodeIgniter 3.x: insert_batch
For CodeIgniter 2.x: insert_batch

CakePHP 2.3 - Unit testing User Login

I thought I have to ask here some help to my problem. I've spend whole evening with this. I have a login method in UsersController like this:
public function login() {
if ( $this->request->is( 'post' ) ) {
if ( $this->Auth->login() ) {
$this->redirect( array( 'controller' => 'reservations', 'action' => 'index' ) );
} else {
$this->Session->setFlash( __( 'Login error.' ), 'flashError' );
}
}
}
I trying to test this with PHPUnit, so I can be sure that only valid users can login → after a successful login they will be redirected to a specific page. Here's my testLogin method in UsersControllerTest class:
function testLogin() {
$UsersController = $this->generate( 'Users', array(
'components' => array(
'Auth' => array( 'user' )
),
)
);
$UsersController->Auth->expects( $this->any() )
->method( 'user' )
->with( 'id' )
->will( $this->returnValue( 2 ) );
$data = array( 'User' => array(
'student_number' => 1111111,
'password' => 'qwerty'
) );
//$UsersController->Auth->login( $data['User'] );
$this->testAction( '/users/login', array( 'data' => $data, 'method' => 'get' ) );
$url = parse_url( $this->headers['Location'] );
$this->assertEquals( $url['path'], '/reservations' );
}
I am still learning the basics of unit testing with CakePHP. I get this error:
PHPUNIT_FRAMEWORK_ERROR_NOTICE
Undefined index: Location
Test case: UsersControllerTest(testLogin)
I have no idea what causes this... What's wrong with my test method and how it should be written?
Thanks!
I got this working with the following code:
function testLogin() {
//mock user
$this->Users = $this->generate( 'Users', array(
'components' => array(
'Security' => array( '_validatePost' ),
)
) );
//create user data array with valid info
$data = array();
$data['User']['student_number'] = 1234567;
$data['User']['password'] = '[valid password here]';
//test login action
$result = $this->testAction( "/users/login", array(
"method" => "post",
"return" => "contents",
"data" => $data
)
);
$foo[] = $this->view;
//debug($foo);
//test successful login
$this->assertNotNull( $this->headers['Location'] );
$this->assertContains( 'reservations', $this->headers['Location'] );
$this->assertNotContains( '"/users/login" id="UserLoginForm"', $foo );
//logout mocked user
$this->Users->Auth->logout();
}
I use this testcase to override the cake Auth call and Session and check if the login is successful.
this is more of a generic solution that i use in my testing., to get the values put into the session after the user logs in and also to check if the login is successful.
<?php
App::uses('UsersController', 'Controller');
App::uses('AuthComponent', 'Controller/Component');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
$_SERVER['HTTP_USER_AGENT'] = '';
class stubSession {
public $data = array();
public function write($key, $value){
$this->data[$key] = $value;
}
public function read($key){
if(array_key_exists($key, $this->data)){
return $this->data[$key];
}
}
public function renew() {
}
public function setFlash(){
}
public function delete() {
}
public function check(){
}
}
class stubRequest {
public $data = array();
function __construct($data) {
$this->data = $data;
}
public function is() {
return true;
}
public function clientIp(){
}
}
class stubAuthComponent extends AuthComponent{
public static $_session;
public function __construct($args, $session){
parent::__construct($args);
$this->Session = $session;
self::$_session = $session;
$this->request = new CakeRequest();
$this->response = new CakeResponse();
}
public function loggedIn() {
return self::$_session->read(self::$sessionKey) != array();
}
public function logout(){
}
public static function user($key) {
$user = self::$_session->read(self::$sessionKey);
return $user[$key];
}
}
class UsersControllerTest extends UsersController {
function __construct($data){
$this->User = ClassRegistry::init('User');
$this->Session = new stubSession();
$this->Auth = new stubAuthComponent(new ComponentCollection(), $this->Session);
$this->request = new stubRequest($data);
}
public function redirect(){
}
}
class TestUsersController extends CakeTestCase {
public function testLogin(){
$_POST = array('User' => array('email' => 'mail#someemail.com', 'username' => 'mail#someemail.com', 'password' => 'abcd1234'));
$usersController = new UsersControllerTest($_POST);
$usersController->login();
$login = $usersController->Auth->loggedIn();
//debug($usersController->Session->data); //you can test the session key value in here
$this->assertEquals($login, true);
}
}

Categories