i have a controller called main...
here i have this code.
$data['companies'] = $this->companies->getAllCompanies();
$this->load->view('main_view',$data);
i have loaded the model called companies in the contructer like this:
$this->load->model('companies');
and this is my model:
class Companies extends CI_Model{
function getAllCompanies()
{
$this -> db -> select('*');
//$this -> db -> from('companies');
$query = $this -> db -> get('companies');
if($query -> num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}}
i am getting this error:
( ! ) Fatal error: Call to a member function execute() on a non-object in C:\wamp\www\awt\system\database\drivers\pdo\pdo_driver.php on line 193
Call Stack
5 0.0299 4303144 Companies->getAllCompanies( ) ..\main.php:32
whats wrong in this code plz help me!
Sounds like that you have some kind of sql error. Try enabling the db_debug flag in application/config/database.php and check the table names and such. You can try to print the generated sql query at where at the place of the error too (under system/database/drivers/pdo/pdo_driver.php:191).
class Companies extends CI_Model{
function getAllCompanies()
{
$this -> db -> select('*');
//$this -> db -> from('companies');
$result = $this -> db -> get('companies');
if($query -> num_rows() > 0)
{
return $result;
}
else
{
return false;
}
}}
make the above changes.
Related
I know this has been asked on here many, many times before, but I am trying to optimize our company gateway for mobile. This was contracted out in 2016 but the guy that started building it wasn't building it for mobile. And he didn't finish it. Now, please know I cut my teeth on ASP.Net so PHP is not my forte, but I inherited this project to finish it. It was built with CodeIgniter 2.2 and I can't upgrade it. Everything mobile (that I work on) will be built using Bootstrap (latest version), as I love Bootstrap and how easy it makes building things with "mobile-first" in mind. So I don't want to try changing all the layout and files that he built because everything is working and displaying really good in all the browsers, but not for mobile. Also know that I have looked at EVERY example that I could find on here (SO). I have tried everything. Problem is, I CAN get my "mobile" login view to display, but what I DON'T know is where to go from there. Do I create separate models and controllers just for the mobile pages that I will be building out? I will show example code of what I've tried below and what has worked. Has anyone tried anything like this and have a working example? At least have enough code that you could point me in the right direction? I would HIGHLY appreciate it. Wracking my brains here. Oh yeah, and I did update the user_agent code from the latest version of CodeIgniter (3.1.11) to catch all the latest mobile browsers because I know CI 2.2 is a little outdated. Btw, I tried to supply as much information as possible as it is working if you visit with a regular computer it shows the regular login page and it logs in just fine. If however you visit with a mobile device, it displays the mobile login page, but will not log in. Just refreshes the page. No matter if I go the user_agent route and use the same URL, or if I go the Detect_Mobile.php route and load the mobi.gatewayurl.com page.
Ok, so here's the layout that's on the host. Sorry I know this is complicated, but all this layout was already done, all I added was the mobile and mobi directories.
|--public_html
|--gateway
|--gw_application
|--controllers
|--account.php
|--administrator.php
|--login.php
|--core
|--MY_Loader.php
|--helpers
|--hooks
|--models
|--account_model.php
|--administrator_model.php
|--login_model.php
|--other models as well
|--third_party
|--Mobile_Detect.php <== Was also playing around with this as well.
|--views
|--account
|--dashboard.php
|--All the other views for the regular users.
|--administrator <== Depending on what role they play. A few users will be an Administrator.
|--dashboard.php
|--All the other views for the Administrators. Which should only be a few people. Most will fall under "account".
|--mobile <== Do I put another set of models and controllers in here?
|--account <== Copied all views from the account directory for regular users in here as well.
|--templates <== The mobile login page loads by putting in a blank header.php, heading.php, and footer.php in here. Otherwise it throws errors if I don't have these in here.
|--login.php <== Or I tried even naming it mlogin.php for mobile, but it won't login. It loads, but just refreshes the page.
|--templates
|--admin
|--header.php
|--heading.php
|--footer.php
|--header.php
|--heading.php
|--footer.php
|--login.php <== The MAIN login page when visiting through a normal browser.
|--gw-system
|--core
|--blah blah
|--mobi <== Also this works using Detect_Mobile.php redirecting it to here with the URL as https://mobi.ourgatewayurl.com.
And here's my MY_Loader.php file that I got from SO article 13928677.
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader
{
//overides existing view function
function view($view, $vars = array(), $return = FALSE)
{
$CI =& get_instance();
$CI->load->library("user_agent");
if($CI->agent->is_mobile()){
$view = 'mobile/'.$view;// <== This does diplay my mobile login page without changing the URL.
}
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
}
//This works good to keep the same URL, such as https://gateway.ourgatewayurl.com, but where to go from here? Otherwise using Mobile_Detect.php, I
//can redirect to https://mobi.ourgatewayurl.com. That would be no problem as well, I can do the subdomain thing, but again, where to go from here?
?>
Here's the login.php controller. Again, I didn't write this, it was already done.
<?php
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->model('login_model');
$this->load->model('setting_model');
$this->load->model('producer_model');
$this->load->model('company_model');
$this->load->model('report_model');
$this->load->model('administrator_model');
}
public function index()
{
$data['settings'] = $this->setting_model->get_setting();
$data['bad_login'] = 0;
if ($this->input->post('username')) {
$data['login'] = $this->login_model->get_login($this->input->post('username'),$this->input->post('password'));
if ($data['login'] == '0') {
$level = $this->session->userdata('user_level');
if ($level == 'administrator') {
$data['message_list'] = $this->administrator_model->get_message();
$this->load->view('templates/admin/heading', $data);
$this->load->view('templates/admin/header', $data);
$this->load->view('administrator/dashboard', $data);
$this->load->view('templates/admin/footer', $data);
$this->load->view('administrator/leftmenu', $data);
} else {
$data['company'] = $this->company_model->get_company($this->session->userdata('company_id'));
$data['producer'] = $this->producer_model->get_producer($this->session->userdata('producer_id'));
$data['message_list'] = $this->administrator_model->get_message();
$this->load->view('templates/admin/heading', $data);
$this->load->view('templates/admin/header', $data);
$this->load->view('account/dashboard', $data);
$this->load->view('templates/admin/footer', $data);
$this->load->view('account/leftmenu', $data);
}
} else {
$data['bad_login'] = 1;
$data['login'] = '1';
$this->load->view('templates/heading', $data);
$this->load->view('templates/header', $data);
$this->load->view('login', $data);
$this->load->view('templates/footer', $data);
}
} else {
$data['login'] = '1';
$this->load->view('templates/heading', $data);
$this->load->view('templates/header', $data);
$this->load->view('login', $data);
$this->load->view('templates/footer', $data);
}
}
}
?>
Here's part of the account.php controller. I left a lot of it out.
<?php
//Only showing for index and dashboard, but he has a public function for every page he has on the gateway.
class Account extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->library('My_PHPMailer');
$this->load->model('account_model');
$this->load->model('setting_model');
$this->load->model('user_model');
$this->load->model('producer_model');
$this->load->model('company_model');
$this->load->model('email_model');
$this->load->model('report_model');
$this->load->model('pagenate_model');
$this->load->model('staff_model');
$this->load->model('signup_model');
if (!$this->session->userdata('user_id') || ($this->session->userdata('user_level') != 'corporate' && $this->session->userdata('user_level') != 'branch' && $this->session->userdata('user_level') != 'producer')) {
header("Location: " . base_url() . 'index.php?/login/logout/');
die();
}
}
public function index()
{
$data['settings'] = $this->setting_model->get_setting();
$data['company'] = $this->company_model->get_company($this->session->userdata('company_id'));
$data['producer'] = $this->producer_model->get_producer($this->session->userdata('producer_id'));
$data['message_list'] = $this->account_model->get_message();
$this->load->view('templates/admin/heading', $data);
$this->load->view('templates/admin/header', $data);
$this->load->view('account/dashboard', $data);
$this->load->view('templates/admin/footer', $data);
$this->load->view('account/leftmenu', $data);
}
public function dashboard()
{
$data['settings'] = $this->setting_model->get_setting();
$data['company'] = $this->company_model->get_company($this->session->userdata('company_id'));
$data['producer'] = $this->producer_model->get_producer($this->session->userdata('producer_id'));
$data['message_list'] = $this->account_model->get_message();
$this->load->view('templates/admin/heading', $data);
$this->load->view('templates/admin/header', $data);
$this->load->view('account/dashboard', $data);
$this->load->view('templates/admin/footer', $data);
$this->load->view('account/leftmenu', $data);
}
}
?>
And here's the login model.
<?php
class Login_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_login($username, $password)
{
$this -> db -> select('*');
$this -> db -> from('user');
$this -> db -> where('user_email = ' . "'" . $this->db->escape_str($username) . "'");
$this -> db -> where('user_password = ' . "'" . $this->db->escape_str(do_hash($password, 'md5')) . "'");
$this -> db -> where('user_is_deleted = 0');
$this -> db -> limit(1);
$query = $this -> db -> get();
$user = $query->row_array();
if($query -> num_rows() == 1) {
$this -> db -> select('*');
$this -> db -> from('user_level');
$this -> db -> where('user_level_id = ' . $user['user_level_id']);
$this -> db -> where('user_level_is_deleted = 0');
$this -> db -> limit(1);
$query2 = $this -> db -> get();
$user_level = $query2->row_array();
$pid = '';
$coid = '';
$ctype = '';
if ($user_level['user_level_name'] != 'administrator') {
$this -> db -> select('*');
$this -> db -> from('producer');
$this -> db -> where('user_id = ' . $user['user_id']);
$this -> db -> limit(1);
$query2 = $this -> db -> get();
$producer = $query2->row_array();
$this -> db -> select('*');
$this -> db -> from('company');
$this -> db -> where('company_id = ' . $producer['company_id']);
$this -> db -> limit(1);
$query3 = $this -> db -> get();
$company = $query3->row_array();
$pid = $producer['producer_id'];
$coid = $producer['company_id'];
$ctype = $company['company_type_id'];
}
$newdata = array(
'user_id' => $user['user_id'],
'producer_id' => $pid,
'company_id' => $coid,
'company_type_id' => $ctype,
'user_level_id' => $user['user_level_id'],
'user_level' => $user_level['user_level_name'],
'user_name' => $user['user_first_name'] . ' ' . $user['user_last_name']
);
$this->session->set_userdata($newdata);
return '0';
} else {
$_SESSION['user_id'] = '';
$_SESSION['producer_id'] = '';
$_SESSION['company_id'] = '';
$_SESSION['company_type_id'] = '';
$_SESSION['user_level_id'] = '';
$_SESSION['user_level'] = '';
$_SESSION['user_name'] = '';
return '1';
}
}
}
?>
Sorry guys this is SO LONG. I just wanted everyone to see how this was laid out and how he had the code written. ANY help will be HIGHLY appreciated. Thanks so much.
Nevermind, I've decided to convert the whole thing to Bootstrap. Its just better if I do that. It needs to be anyway. Bootstrap works so good for mobile anyway.
I'm working on a project using CakePHP 3.x.
I have UserAddress, ServiceRequests, Service models.
There is a button on service/view/$id which when clicked will ask user to select address from service-requests/serviceArea which has a list of addresses added by user. service-requests/serviceArea view will contain a select button which when clicked will call add action in ServiceRequests controller with passing two parameters serviceId and userAddressId
This is the serviceArea function created by me.
public function serviceArea($id = null)
{
public $uses = array('UserAddress');
$service = $id;
$query = $userAddresses->find('all')
->where(['UserAddresses.user_id =' => $this->Auth->user('id')]);
$this->set(compact('userAddresses'));
$this->set('_serialize', ['userAddresses']);
}
How to display the address and also pass the $service parameter to the serviceArea view.
I am new to CakePHP, so if you think question is incomplete any edit to it will be appreciated instead of down-voting.
Thank You.
Edit 2
Thank for your answer #jazzcat
After changing my code according to yours and visiting http://domain.com/service-requests/service-area/$id. It is showing error as
Record not found in table "service_requests"
and pointing to the ServiceRequestsController on line no 33
The ServiceRequestController as containing line no 33 is
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* ServiceRequests Controller
*
* #property \App\Model\Table\ServiceRequestsTable $ServiceRequests
*/
class ServiceRequestsController extends AppController
{
/**
* isAuthorized method
*
*/
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// The add and index actions are always allowed.
if(in_array($action, ['index', 'add', 'serviceRequests'])) {
return true;
}
// All other actions require an id.
if (empty($this->request->params['pass'][0])) {
return false;
}
// Check that the service request belongs to the current user.
$id = $this->request->params['pass'][0];
$serviceRequest = $this->ServiceRequests->get($id); // line : 33
if($serviceRequest->user_id == $user['id']) {
return true;
}
return parent::isAuthorized($user);
}
/* Other actions */
}
?>
This worked for me.
Just added the serviceArea action name in the isAuthorized method
if(in_array($action, ['index', 'add', 'serviceArea'])) {
return true;
}
and it's working fine as expected.
There is alot wrong with your code. Please read the docs
Is the table named user_addresses or user_address ?
You seem to mix the both.
The following would be the correct way to do it assuming your table is named user_addresses
public function serviceArea($id = null)
{
$this->loadModel('UserAddresses');
$userAddresses = $this->UserAddresses->find('all')
->where(['UserAddresses.user_id =' => $this->Auth->user('id')]);
// If you want to filter on the serviceArea ID aswell
if($id)
$userAddresses->andWhere(['id' => $id]);
// Setting SerivceArea ID to compact makes it available in view.
$serviceAreaId = $id;
$this->set(compact('userAddresses', 'serviceAreaId'));
$this->set('_serialize', ['userAddresses']);
}
This snippet:
$id = $this->request->params['pass'][0];
$serviceRequest = $this->ServiceRequests->get($id); // line : 33
Just checks if the first parameter passed to the method exists in ServiceRequests.
(That parameter could be anything, you have to keep that in mind when creating all your methods in that controller, that is to say the least.. bad)
I'm assuming that the service_requests table is associated with the users table and an user_id column exists in the service_requests table.
If that is the case this should work:
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// The add and index actions are always allowed.
if(in_array($action, ['index', 'add'])) {
return true;
}
// Is not authorized if an argument is not passed to the method.
// Don't know why you'd want this , but sure.
if (empty($this->request->params['pass'][0])) {
return false;
}
// Check that the service request belongs to the current user.
$user_id = $this->Auth->user('id');
$serviceRequest = $this->ServiceRequests->find()->where(['ServiceRequests.user_id' => $user_id])->first();
if(!empty($serviceRequest)) {
return true;
}
return parent::isAuthorized($user);
}
I am being shown the following error on top of my page when using beforeSave method in my Upload model.
Strict (2048): Declaration of Upload::beforeSave() should be
compatible with Model::beforeSave($options = Array)
[APP/Model/Upload.php, line 5]
Could someone point out what I'm doing wrong?
Here is my model:
<?php
App::uses('AppModel', 'Model');
class Upload extends AppModel {
protected function _processFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$name = md5($file['name']);
$path = WWW_ROOT . 'files' . DS . $name;
if (is_uploaded_file($file['tmp_name'])
&& move_uploaded_file($file['tmp_name'], $path) ) {
$this->data['Upload']['name'] = $file['name'];
$this->data['Upload']['size'] = $file['size'];
$this->data['Upload']['mime'] = $file['type'];
$this->data['Upload']['path'] = '/files/' . $name;
unset($this->data['Upload']['file']);
return true;
}
}
return false;
}
public function beforeSave() {
if (!parent::beforeSave($options)) {
return false;
}
return $this->_processFile();
}
}
?>
Just change this line
public function beforeSave() {
to this, so you have correct method declaration
public function beforeSave($options = array()) {
The beforeSave() function executes immediately after model data has been successfully validated, but just before the data is saved. This function should also return true if you want the save operation to continue.
This callback is especially handy for any data-massaging logic that needs to happen before your data is stored. If your storage engine needs dates in a specific format, access it at $this->data and modify it.
Below is an example of how beforeSave can be used for date conversion. The code in the example is used for an application with a begindate formatted like YYYY-MM-DD in the database and is displayed like DD-MM-YYYY in the application. Of course this can be changed very easily. Use the code below in the appropriate model.
public function beforeSave($options = array()) {
if (!empty($this->data['Event']['begindate']) &&
!empty($this->data['Event']['enddate'])
) {
$this->data['Event']['begindate'] = $this->dateFormatBeforeSave(
$this->data['Event']['begindate']
);
$this->data['Event']['enddate'] = $this->dateFormatBeforeSave(
$this->data['Event']['enddate']
);
}
return true;
}
public function dateFormatBeforeSave($dateString) {
return date('Y-m-d', strtotime($dateString));
}
Make sure that beforeSave() returns true, or your save is going to fail.
I have a specific task to connect CakePHP web application to a remote restful server . I create a datasource, read method works great, but the api after save data return an array of processed data.
Looking for a way to return the data array and use in controller.
My Controller code
public function admin_generate()
{
$data = $this->request->data;
$data['path'] = 'special/generate';
$this->Tool->create();
if($this->Tool->save($data)){
// handle response ????
}
$this->set('data',$data);
$this->set('_serialize','data');
}
In datasource file
public function create(Model $model, $fields = null, $values = null)
{
$data = array_combine($fields, $values);
$api = $this->config['api_path'].$data['path'].'?auth_key='.$this->config['auth_key'];
$json = $this->Http->post($api, $data);
$response = json_decode($json, true);
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
return $response; // ??????
}
Can someone show me the correct way to use the api response data in the controller?
I found a solution, a few minutes after a post question. This can help one of you.
datasource
....
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
// SOLUTION
$model -> code = $response['code'];
$model -> key = $response['key'];
$model -> code_id = $response['code_id'];
return true;
.....
in controller
.....
if($this->Tool->save($data)){
unset($data['path']);
$data['code'] = $this->Tool->code;
$data['key'] = $this->Tool->key;
$data['code_id'] = $this->Tool->code_id;
}
.....
I am working on a CakePHP 2.x. The scenario is I am sending an encrypted and decrypted data to the database. So in order to do this I have written beforeSave function in each modal.
so right now the problem is whenever data is updated, the data is not going encrypted into db .. please anyone know how to i fix this issue
I am doing this in my controller. The update and save function:
foreach($data as $datas){
$count = $this->Contact->checkkey($datas['idUser'],$datas['key']);
if($count>0){
$this->Contact->updateContactAgainstkey($datas['name'],
$this->request->data['Contact']['mobileNo'],
$this->request->data['Contact']['other'],
$this->request->data['Contact']['email'],
$datas['key'],$datas['idUser']);
}else{
$this->Contact->create();
$this->Contact->save($this->request->data);
}
}
updateFunction in Model
public function updateContactAgainstkey($name,$mobileNo,
$other,$email,$key,$userid){
if($this->updateAll(
array('name' => "'$name'",
'mobileNo' => "'$mobileNo'",
'workNo' => "'$workNo'",
'homeNo' => "'$homeNo'",
'other' => "'$other'",
'email' => "'$email'",),
array('User_id'=>$userid,'key'=>$key))){
return true;
}else{
return false;
}
}
beforeSave function
public function beforeSave($options=array()) {
if ( isset ( $this -> data [ $this -> alias ] [ 'mobileNo' ] ) ) {
$this -> data [ $this -> alias ] [ 'mobileNo' ] = AllSecure::encrypt($this->data[$this->alias]['email']);
}
return true;
}
please help me if anyone know how to deal with this issue.
Try following code in model
public function updateAll($fields, $conditions = true) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$created = FALSE;
$options = array();
if($db->update($this, $fields, null, $conditions)) {
$created = TRUE;
$this->Behaviors->trigger($this, 'afterSave', array($created, $options));
$this->afterSave($created);
$this->_clearCache();
$this->id = false;
return true;
}
return FALSE;
}
look here
http://nuts-and-bolts-of-cakephp.com/2010/01/27/make-updateall-fire-behavior-callbacks/
here better to use save function for updating data like:
$data=array();
$data['Contact']['mobileNo']=$this->request->data['Contact']['mobileNo'];
$data['Contact']['other']=$this->request->data['Contact']['other'];
$data['Contact']['other']=$this->request->data['Contact']['other'];
........... .............. ................
$this->Contact->id = "primerykey";
$this->Contact->save($data);
where $data contains all field that you want to update with value