how to insert data in database using cakephp - mysql

i have a table name stores and i have controller name is StoresController.php and model name is Stores.php and have a add.ctp file inside Stores folder but i an unable to insert data from form.here is my add.ctp file
<div class="row form-main">
<div class="panel panel-default">
<div class="panel-body">
<?php echo $this->Form->create('Store', array('class'=>"contact-
form"));
?>
<div class="form-group">
<div class="col-sm-6">
<?php
echo $this->Form->input('name',array('required'=>false,'class'=>"form-
control", 'placeholder'=>"Enter Name","label"=>false));
?>
</div>
<div class="col-sm-6">
<?php
echo $this->Form-
>input('address1',array('required'=>false,'class'=>"form-control",
'placeholder'=>"Enter Address1","label"=>false));
?>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" value="Submit" class="btn
btn-success">
<button type="submit" class="btn btn-info">Cancel</button>
</div>
</div>
<?php echo $this->Form->end(); ?>
here is my StoresController.php
<?php
App::uses('AppController', 'Controller');
class StoresController extends AppController {
var $uses = array();
var $component = array("Common");
public $paginate = array();
public function add(){
$this->layout = 'user_layout';
$user_id = $this->UserAuth->getUserId();
$owner_id = $this->Common->getOwnerId($user_id);
if ($this->request->is('post')) {
$this->Store->create();
if ($this->Store->save($this->request->data)) {
$this->Flash->success(__('User has been Added'));
return $this->redirect(array('action' => 'add'));
} $this->Flash->error(__('Unable to add your post.'));
}
}
}
?>
and i am getting error Call to a member function create() on a non-object in controller

you should be using:
$this->Form->create('Store');
public function add(){
$this->layout = 'user_layout';
$user_id = $this->UserAuth->getUserId();
$owner_id = $this->Common->getOwnerId($user_id);
if ($this->request->is('post')) {
$this->Store->create('Store');
if ($this->Store->save($this->request->data)) {
$this->Flash->success(__('User has been Added'));
return $this->redirect(array('action' => 'add'));
} $this->Flash->error(__('Unable to add your post.'));
}
}

Yes, I solved the problem. There was a minor problem. I forgot the following line in the controller:
var $uses = array('Store');

Related

I can't save input to database Vuejs and Laravel

I added two new input (ass1 and ass2) to a form, created the columns in the database, added it to $fillable in the model, and method in Vue file.
The challenge is that every other input saves to the database but my new inputs are not stored to the database.
If I input directly to the database, the data will show up for edit/update but will not store.
I have checked and checked through the code and can't find any issue, no error message so far.
If you need any other details I will be happy to provide them.
Please help! I'm on a deadline.
P.S. I have very little knowledge of Vuejs, it's a bit confusing.
This is my form.vue content:
<template>
<div>
<form #submit.prevent="proceed" #keydown="assessmentForm.errors.clear($event.target.name)">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">{{trans('exam.assessment_name')}}</label>
<input class="form-control" type="text" v-model="assessmentForm.name" name="name" :placeholder="trans('exam.assessment_name')">
<show-error :form-name="assessmentForm" prop-name="name"></show-error>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">{{trans('exam.assessment_description')}}</label>
<input class="form-control" type="text" v-model="assessmentForm.description" name="description" :placeholder="trans('exam.assessment_description')">
<show-error :form-name="assessmentForm" prop-name="description"></show-error>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<h6 class="card-title">{{trans('exam.assessment_type')}}</h6>
<template v-for="(detail,index) in assessmentForm.details">
<div class="row">
<div class="col-12 col-sm-3">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_name')}}
<button type="button" class="btn btn-xs btn-danger m-l-20" :key="`${index}_delete_detail`" v-confirm="{ok: confirmDeleteDetail(index)}" v-tooltip="trans('general.delete')"><i class="fas fa-times"></i></button></label>
<input class="form-control" type="text" v-model="detail.name" :name="getDetailName(index)" :placeholder="trans('exam.assessment_detail_name')">
<show-error :form-name="assessmentForm" :prop-name="getDetailName(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-1">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_code')}}</label>
<input class="form-control" type="text" v-model="detail.code" :name="getDetailCode(index)" :placeholder="trans('exam.assessment_detail_code')">
<show-error :form-name="assessmentForm" :prop-name="getDetailCode(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_max_mark')}}</label>
<input class="form-control" type="number" v-model="detail.max_mark" :name="getDetailMaxMarkName(index)" :placeholder="trans('exam.assessment_detail_max_mark')">
<show-error :form-name="assessmentForm" :prop-name="getDetailMaxMarkName(index)"></show-error>
</div>
</div>
<!-- <div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_pass_percentage')}}</label>
<div class="input-group mb-3">
<input class="form-control" type="number" v-model="detail.pass_percentage" :name="getDetailPassPercentageName(index)" :placeholder="trans('exam.assessment_detail_pass_percentage')">
<div class="input-group-append">
<span class="input-group-text" id="basic-addon1">%</span>
</div>
</div>
<show-error :form-name="assessmentForm" :prop-name="getDetailPassPercentageName(index)"></show-error>
</div>
</div> -->
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_ass1')}}</label>
<input class="form-control" type="number" v-model="detail.ass1" :name="getDetailAssessment1(index)" :placeholder="trans('exam.assessment_detail_ass1')">
<show-error :form-name="assessmentForm" :prop-name="getDetailAssessment1(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_ass2')}}</label>
<input class="form-control" type="number" v-model="detail.ass2" :name="getDetailAssessment2(index)" :placeholder="trans('exam.assessment_detail_ass2')">
<show-error :form-name="assessmentForm" :prop-name="getDetailAssessment2(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_description')}}</label>
<autosize-textarea v-model="detail.description" rows="2" :name="getDetailDescriptionName(index)" :placeholder="trans('resource.assessment_detail_description')"></autosize-textarea>
<show-error :form-name="assessmentForm" :prop-name="getDetailDescriptionName(index)"></show-error>
</div>
</div>
</div>
</template>
<div class="form-group">
<button type="button" #click="addRow" class="btn btn-info btn-sm waves-effect waves-light">{{trans('exam.add_new_assessment_detail')}}</button>
</div>
</div>
</div>
<div class="card-footer text-right">
<router-link to="/configuration/exam/assessment" class="btn btn-danger waves-effect waves-light ">{{trans('general.cancel')}}</router-link>
<button type="submit" class="btn btn-info waves-effect waves-light">
<span v-if="id">{{trans('general.update')}}</span>
<span v-else>{{trans('general.save')}}</span>
</button>
</div>
</form>
</div>
</template>
<script>
export default {
components: {},
data() {
return {
assessmentForm: new Form({
name: '',
description: '',
// details: ['name', 'code', 'max_mark', 'ass1', 'ass2', 'description']
details: []
})
};
},
props: ['id'],
mounted() {
if(!helper.hasPermission('access-configuration')){
helper.notAccessibleMsg();
this.$router.push('/dashboard');
}
if(this.id)
this.get();
else {
this.addRow();
}
},
methods: {
hasPermission(permission){
return helper.hasPermission(permission);
},
addRow(){
let new_index = this.assessmentForm.details.push({
name: '',
code: '',
max_mark: '',
ass1: '',
ass2: '',
// pass_percentage: '',
description: ''
})
},
confirmDeleteDetail(index){
return dialog => this.deleteDetail(index);
},
deleteDetail(index){
this.assessmentForm.details.splice(index, 1);
},
getDetailName(index){
return index+'_detail_name';
},
getDetailCode(index){
return index+'_detail_code';
},
getDetailMaxMarkName(index){
return index+'_detail_max_mark';
},
// getDetailPassPercentageName(index){
// return index+'_detail_pass_percentage';
// },
getDetailAssessment1(index){
return index+'_detail_ass1';
},
getDetailAssessment2(index){
return index+'_detail_ass2';
},
getDetailDescriptionName(index){
return index+'_detail_description';
},
proceed(){
if(this.id)
this.update();
else
this.store();
},
store(){
let loader = this.$loading.show();
this.assessmentForm.post('/api/exam/assessment')
.then(response => {
toastr.success(response.message);
this.assessmentForm.details = [];
this.addRow();
this.$emit('completed');
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
},
get(){
let loader = this.$loading.show();
axios.get('/api/exam/assessment/'+this.id)
.then(response => {
this.assessmentForm.name = response.name;
this.assessmentForm.description = response.description;
response.details.forEach(detail => {
this.assessmentForm.details.push({
name: detail.name,
code: detail.code,
max_mark: detail.max_mark,
ass1: detail.ass1,
ass2: detail.ass2,
description: detail.description
// pass_percentage: detail.pass_percentage,
});
});
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
this.$router.push('/configuration/exam/assessment');
});
},
update(){
let loader = this.$loading.show();
this.assessmentForm.patch('/api/exam/assessment/'+this.id)
.then(response => {
toastr.success(response.message);
loader.hide();
this.$router.push('/configuration/exam/assessment');
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
}
}
}
</script>
This is the model (AssessmentDetail.php):
<?php
namespace App\Models\Configuration\Exam;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
class AssessmentDetail extends Model
{
use LogsActivity;
protected $fillable = [
'exam_assessment_id',
'name',
'max_mark',
'ass1',
'ass2',
// 'pass_percentage',
'description',
'options'
];
protected $casts = ['options' => 'array'];
protected $primaryKey = 'id';
protected $table = 'exam_assessment_details';
protected static $logName = 'exam_assessment_detail';
protected static $logFillable = true;
protected static $logOnlyDirty = true;
protected static $ignoreChangedAttributes = ['updated_at'];
public function assessment()
{
return $this->belongsTo('App\Models\Configuration\Exam\Assessment', 'exam_assessment_id');
}
public function getOption(string $option)
{
return array_get($this->options, $option);
}
public function scopeFilterById($q, $id)
{
if (! $id) {
return $q;
}
return $q->where('id', '=', $id);
}
public function scopeFilterByExamAssessmentId($q, $exam_assessment_id)
{
if (! $exam_assessment_id) {
return $q;
}
return $q->where('exam_assessment_id', '=', $exam_assessment_id);
}
public function scopeFilterByName($q, $name, $s = 0)
{
if (! $name) {
return $q;
}
return $s ? $q->where('name', '=', $name) : $q->where('name', 'like', '%'.$name.'%');
}
}
This is my Controller (AssessmentController)
<?php
namespace App\Http\Controllers\Configuration\Exam;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Configuration\Exam\AssessmentRequest;
use App\Repositories\Configuration\Exam\AssessmentRepository;
class AssessmentController extends Controller
{
protected $request;
protected $repo;
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct(
Request $request,
AssessmentRepository $repo
) {
$this->request = $request;
$this->repo = $repo;
$this->middleware('permission:access-configuration');
$this->middleware('academic.session.set');
}
/**
* Used to get all Exam Assessments
* #get ("/api/exam/assessment")
* #return Response
*/
public function index()
{
return $this->ok($this->repo->paginate($this->request->all()));
}
/**
* Used to print all Exam Assessments
* #post ("/api/exam/assessment/print")
* #return Response
*/
public function print()
{
$exam_assessments = $this->repo->print(request('filter'));
return view('print.configuration.exam.assessment', compact('exam_assessments'))->render();
}
/**
* Used to generate pdf all Exam Assessments
* #post ("/api/exam/assessment/pdf")
* #return Response
*/
public function pdf()
{
$exam_assessments = $this->repo->print(request('filter'));
$uuid = Str::uuid();
$pdf = \PDF::loadView('print.configuration.exam.assessment', compact('exam_assessments'))->save('../storage/app/downloads/'.$uuid.'.pdf');
return $uuid;
}
/**
* Used to store Exam Assessment
* #post ("/api/exam/assessment")
* #param ({
* #Parameter("name", type="string", required="true", description="Name of Exam Assessment"),
* #Parameter("description", type="text", required="optional", description="Description of Exam Assessment")
* })
* #return Response
*/
public function store(AssessmentRequest $request)
{
$exam_assessment = $this->repo->create($this->request->all());
// dd('$exam_assessment');
return $this->success(['message' => trans('exam.assessment_added')]);
}
/**
* Used to get Exam Assessment detail
* #get ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* })
* #return Response
*/
public function show($id)
{
return $this->ok($this->repo->findOrFail($id));
}
/**
* Used to update Exam Assessment
* #patch ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* #Parameter("name", type="string", required="true", description="Name of Exam Assessment"),
* #Parameter("description", type="text", required="optional", description="Description of Exam Assessment")
* })
* #return Response
*/
public function update($id, AssessmentRequest $request)
{
$exam_assessment = $this->repo->findOrFail($id);
$exam_assessment = $this->repo->update($exam_assessment, $this->request->all());
return $this->success(['message' => trans('exam.assessment_updated')]);
}
/**
* Used to reorder all Details of assessment
* #frontend ("/api/exam/assessment/{id}/reorder")
* #return Response
*/
public function reorder($id)
{
$exam_assessment = $this->repo->findOrFail($id);
$this->repo->reorder($exam_assessment, $this->request->all());
return $this->success(['message' => trans('exam.assessment_updated')]);
}
/**
* Used to delete Exam Assessment
* #delete ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* })
* #return Response
*/
public function destroy($id)
{
$exam_assessment = $this->repo->deletable($id);
$this->repo->delete($exam_assessment);
return $this->success(['message' => trans('exam.assessment_deleted')]);
}
}
These are the routes for the Assessment from Api.php
Route::get('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#show');
Route::post('/exam/assessment', 'Configuration\Exam\AssessmentController#store');
Route::patch('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#update');
Route::delete('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#destroy');
Thank you all for your comments.
I finally found the solution.
Apparently, in my controller(AssessmentController) my construct method is getting the input from AssessmentRepository (App\Repository).
public function __construct(
Request $request,
AssessmentRepository $repo
) {
$this->request = $request;
$this->repo = $repo;
$this->middleware('permission:access-configuration');
$this->middleware('academic.session.set');
}
Then $repo is called in my store, update, show, reorder and other methods.
I've never seen or used App\Repositories before.
You learn every day!

Error in wbranca dynagrid update

Am using wbranca yii2 to create dynamic forms but the update action returns an error of
array_combine(): Both parameters should have an equal number of elements
This is the form for the update
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsPrItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'po_item_no',
'quantity',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsPrItem as $i => $modelPrItem): ?>
<div class="item paneld">
<!-- widgetBody -->
<div class="panelf-heading">
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panelf-body">
<?php
// necessary for update action.
if (! $modelPrItem->isNewRecord) {
echo Html::activeHiddenInput($modelPrItem, "[{$i}]PRID");
}
?>
<div class="row">
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Quantity")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Unit_Price")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Extended_price")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Currency_ID")->dropDownList(
ArrayHelper::map(Tblcurrency::find()->all(),'CurrencyID','currency_symbol'),[]
); ?>
</div>
<div class="col-md-4">
<?= $form->field($modelPrItem, "[{$i}]Description")->textArea(['maxlength' => 128]) ?>
</div>
</div>
<!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
This is the model:
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* #param string $modelClass
* #param array $multipleModels
* #return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
$models[] = $multipleModels[$item['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
The above returns an error when i run update especially when updating more than one item
The error message say that the number of element in $keys and $values (alias $multipleModels ) are not the same so you are trying to build an associative array witth a wrong pair of key => value elements
Try var_dump (or inspect with xdebug) the content of the $keys and$multipleModels and adapt the code to your real need .
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
var_dump($keys );
var_dump($multipleModels);
$multipleModels = array_combine($keys, $multipleModels);
}

Flash message shows twice in a view CakePHP3

I've encountered this issue several times and tried to avoid it by removing calling Flash method. Lately, I want to show an error flash to non-logged in user who tries to log out. However, when I test this action(by accessing localhost:8765/users/logout without being logged in), everything works fine except I get 2 error messages "You are not authorized to access this location". How can I fix this issue?
Here are my codes
In AppController:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'], //For User authorize checking, this tells app to let each controller decides own rules for authorize
'loginRedirect' => ['controller' => 'Articles', 'action' => 'index'],
'logoutRedirect' => ['controller' => 'Users', 'action' => 'index']
]);
}
public function beforeFilter(Event $event)
{
//this applied to every controller
$this->Auth->allow(['index', 'view', 'display']);
}
...
public function isAuthorized($user)
{
//Admin can access every action
if(isset($user['role']) && $user['role'] === 'admin'){
return true;
}
//Default deny
return false;
}
In UsersController:
public function isAuthorized($user)
{
//All registered users can add articles
if($this->request->action === 'add'){
return true;
}
//The self user can edit and delete the account
if(in_array($this->request->action, ['edit', 'delete'])){
//get id of targeted user
$targetUserId = (int)$this->request->params['pass'][0];
//check if current user is the targeted user
if($this->Users->selfUser($targetUserId, $user['id'])){
return true;
}else{
$this->Flash->error(__('You are not authorized for this action'));
}
}
return parent::isAuthorized($user);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['add']);
}
...
public function logout()
{
return $this->redirect($this->Auth->logout());
}
In UsersTable
public function selfUser($targetedUserId, $userId)
{
return $targetedUserId == $userId;
}
In default.ctp
$cakeDescription = 'CakePHP: the rapid development php framework';
?>
<!DOCTYPE html>
<html>
<head>
<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<?= $cakeDescription ?>:
<?= $this->fetch('title') ?>
</title>
<?= $this->Html->meta('icon') ?>
<?= $this->Html->css('base.css') ?>
<?= $this->Html->css('cake.css') ?>
<?= $this->fetch('meta') ?>
<?= $this->fetch('css') ?>
<?= $this->fetch('script') ?>
</head>
<body>
<nav class="top-bar expanded" data-topbar role="navigation">
<ul class="title-area large-3 medium-4 columns">
<li class="name">
<h1><?= $this->fetch('title') ?></h1>
</li>
</ul>
<div class="top-bar-section">
<ul class="right">
<li><a target="_blank" href="http://book.cakephp.org/3.0/">Documentation</a></li>
<li><a target="_blank" href="http://api.cakephp.org/3.0/">API</a></li>
</ul>
</div>
</nav>
<?= $this->Flash->render() ?>
<div class="container clearfix">
<?= $this->fetch('content') ?>
</div>
<footer>
</footer>
</body>
</html>
In login.ctp
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Please enter your username and password') ?></legend>
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
Could you also post even just an excerpt from your CTP file? It could be possible that within the page layout the Flash was rendered twice.
You must add this line in your logout action:
$this->autoRender = false;
So, in your case, your UsersController should be:
public function isAuthorized($user)
{
//All registered users can add articles
if($this->request->action === 'add'){
return true;
}
//The self user can edit and delete the account
if(in_array($this->request->action, ['edit', 'delete'])){
//get id of targeted user
$targetUserId = (int)$this->request->params['pass'][0];
//check if current user is the targeted user
if($this->Users->selfUser($targetUserId, $user['id'])){
return true;
}else{
$this->Flash->error(__('You are not authorized for this action'));
}
}
return parent::isAuthorized($user);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['add']);
}
...
public function logout()
{
$this->autoRender = false;
return $this->redirect($this->Auth->logout());
}

Ionic Framework, Populate select (drowdownlist) from database

Where is wrong with below code? I can get the JSON result directly through any browser, it just don't want to show up in the dropdown list
I am just trying to populate from mysql database to combobox in ionic framework.
UPDATED SCRIPT
Still get empty in the dropdown list. Anyone?
addlist.html
<ion-header-bar align-title="center" class="bar-stable">
<h1 class="title">Add Lists</h1>
</ion-header-bar>
<ion-view>
<div class="list has-header padding">
<label class="item item-input item-select">
<div class="input-label">
Category
</div>
<div ng-controller="AddListCategoryCtrl">
<select ng-model="category" ng-options="x.category for x in data">
<option ng-repeat="x in data" value="{{x.id}}">{{x.category}}</option>
</select>
</div>
</label>
</div>
</ion-view>
controllers.js
angular.module('ionicApp.controllers', [])
.controller('AddListCategoryCtrl', function($scope, $http) {
var xhr = $http({
method: 'post',
url: 'http://www.mywebsite.com/api/listCat.php'
});
xhr.success(function(data){
$scope.data = data.data;
});
});
listCat.php
<?php
include 'db.php';
getById();
function getById() {
$sql = "SELECT id,category FROM tbl_category ORDER BY tbl_category.id";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$category = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"category": ' . json_encode($category) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>

Codeigniter Login Form not getting my username and password

I cant seem to login using these codes. Its not fetching the username and password on my database. Can you help me can i work with this? When login button clicked, it will validate if the username exist on the admin table and will check if the password is correct and status is Active. if so, it will go to the main page. if not it will stay on this page and display the error message. Please help
In Controller
function login()
{
//set validations
$this->form_validation->set_rules("username", "username", "trim|required|xss_clean");
$this->form_validation->set_rules("password", "password", "trim|required|xss_clean|callback_check_database");
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login_view');
//$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username or password!</div>');
}
else
{
//Go to private area
redirect('index','refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$user = $this->input->post('username');
//query the database
$result = $this->main_model->get_user($username, $password);
$this->display($result);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-danger text-center">Invalid username or password!</div>');
return false;
}
}
In model
function get_user($username, $password)
{
$sql = "select * from admin where username = '" . $username . "' and password = '" . md5($password) . "' and status = 'Active' limit 1";
$query = $this->db->query($sql);
if($query->num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
In View
<?php
$attributes = array("class"=>"login-form","id"=>"main","name"=>"main");
echo form_open("main/login", $attributes);?>
<body class="login-img3-body">
<div class="container">
<div class="login-wrap">
<p class="login-img">Login</p>
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<input id="username" name="username" type="text" class="form-control" placeholder="Username" value="<?php echo set_value('username'); ?>" autofocus>
<span class="text-danger"><?php echo form_error('username'); ?></span>
</div>
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input id="password" name="password" type="password" class="form-control" placeholder="Password" value="<?php echo set_value('password'); ?>">
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
<span class="pull-right"> Forgot Password?</span>
</label>
<button class="btn btn-primary btn-lg btn-block" id="btn_login" value="Login" type="submit">Login</button>
</div>
</form>
</div>
<?php echo form_close(); ?>
Make sure you load the helper
in __construct()
function __construct() {
parent::__construct();
$this->load->helper('form');
}
In Model
function get_user($username, $password)
{
$query = $this->db->query("select * from admin where username = '$username' and password = 'md5($password)' and status = 'Active' limit 1");
$result = $query->result_array();
$count = count($result);
if($count == 1)
{
return $result;
}
else
{
return false;
}
}
To submit form use this
echo form_submit('mysubmit', 'Submit Post!', 'class="btn btn-primary btn-lg btn-block"');