if( !function_exists('audit') ) {
function addAudit($id_user,$description)
{
$response_audit = $CI->Audit_model->addAudit($id_user,$description);
if($response_audit){
log_message('debug',' Product --addAudit :: Response received from model');
}else{
log_message('debug',' Product --addAudit :: Response didnot received from model');
}
}
}
if( !function_exists('audit') ) {
function addAudit($id_user,$description) {
$CI = &get_instance();
$CI->load->model ( 'Audit_model' );
$response_audit = $CI->Audit_model->addAudit($id_user,$description);
if($response_audit){
log_message('debug',' Product --addAudit :: Response received from model');
}else{
log_message('debug',' Product --addAudit :: Response didnot received from model');
}
}
In constructor of common helper:
public function __construct() {
// Assign the CodeIgniter super-object
$this->CI = & get_instance();
}
//Now for loading a model
public function addAudit($id_user,$description){
$this->CI->load->model('your_model_name');
$response_audit = $this->CI->your_model_name->addAudit($id_user,$description);
if($response_audit){
log_message('debug',' Product --addAudit :: Response received from model');
}else{
log_message('debug',' Product --addAudit :: Response didnot received from model');
}
}
Related
How to get id from url parameter to url function codeigniter4
public function show($id = null)
{
$data = $this->model->where('id', $id)->findAll();
if ($data) {
return $this->respond($data, 200);
} else {
return $this->failNotFound("Data Not Found to $id");
}
}
You can pass the value using post request.
and in controller function you can read like this
public function show( ) {
$id = $this->request->getVar('id');
$data = $this->model->where('id', $id)->findAll();
if ($data) {
return $this->respond($data, 200);
} else {
return $this->failNotFound("Data Not Found to $id");
}
}
I have face this Fatal error: problem in local.
$rr = $this->CI->db->query("select * from $table $condition ");
$mm = $rr->num_rows();
if ($mm>0) {
return 1;
} else {
return 0;
}
<?php
$this->db->select("your stuff");
$query = $this->db->get("your table");
if($query->num_rows() > 0 ) {
return 1;
}
else {
return 0;
}
?>
$this->CI->db->query("select * from $table $condition ");
remove CI and
$this->db->query("select * from $table $condition ");
First have you autoload the database
$autoload['libraries'] = array('database');
If a your trying to load a library then use the $CI instance http://www.codeigniter.com/user_guide/general/ancillary_classes.html#get-instance
application > libraries > Example.php
<?php
class Example {
protected $CI;
public function __construct() {
$this->CI =& get_instance();
}
public function somename() {
$query = $this->CI->db->query("select * from $table $condition ");
if ($query->num_rows() > 0) {
return 1; // return true;
} else {
return 0; // return false;
}
}
}
If on models
application > models > Example_model.php
<?php
class Example_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function somename() {
$query = $this->db->query("select * from $table $condition ");
if ($query->num_rows() > 0) {
return 1; // return true;
} else {
return 0; // return false;
}
}
}
Update one CI core file and resolve your error:
Go to : System/database/ and edit DB_active_rec.php file
Go to line no 990 and see blow code
if ($query->num_rows() == 0)
{
return 0;
}
Update to
if (!$query || $query->num_rows() == 0)
{
return 0;
}
Hope resolved your num_rows() issue.
class Site_m extends MY_Model {
protected $_table_name = 'setting';
protected $_primary_key = 'option';
protected $_primary_filter = 'intval';
protected $_order_by = "option asc";
function __construct() {
parent::__construct();
}
function get_site($id) {
$compress = array();
$query = $this->db->get('setting');
foreach ($query->result() as $row) {
$compress[$row->fieldoption] = $row->value;//here I am getting error
}
return (object) $compress;
}
}
/* End of file site_m.php */
This is fix in core CI-2
File
\system\database\DB_driver.php
Line in code
https://github.com/bcit-ci/CodeIgniter/blob/develop/system/database/DB_driver.php#L659
replace FALSE before end code
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
return FALSE;
}
To
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
$CR = new CI_DB_result();
return $CR;
}
Default should be return object empty
$CR = new CI_DB_result();
return $CR;
I keep getting a 500 internal error every time I try to make an Ajax request. Based on debugging, the 500 error doesn't pop up until the "if" statement in the store function. I can't for the life of me figure out why. When I run the code via regular post requests and discard the Ajax it works fine. Any ideas?:
public function store( Request $request, $project_id ) {
//current logged in user.
$user_id = auth()->user()->id;
//get all post inputs
$inputs = $request->all();
//make sure project ID belongs to current user. Stop someone from adding a task to your project that isn't you.
$projectBelongsToUser = Project::find(1)->where('user_id', $user_id)->where('id', $project_id);
//if a project ID and inputs are provided - log them to the database, if not redirect to home with $errors.
if( $project_id && $inputs['submit'] && $projectBelongsToUser ) {
$task = New Task;
$task->description = $inputs['description'];
$task->due_date = $inputs['due_date'];
$task->priority = $inputs['priority'];
$task->completed = 0;
$task->order = 0;
$task->user_id = $user_id;
$task->project_id = $project_id;
$task->save();
//get all tasks
$tasks = Task::all();
//sanitize tasks for safe output
function sanitize_object_h( $array ) {
$array_modified = $array;
foreach( $array_modified as $object ) {
foreach( $object as &$item ) {
$item = htmlentities( $item, ENT_QUOTES );
}
//end foreach
}
//end foreach
return $array_modified;
}
//end sanitize_object_h
$sanitized_tasks = sanitize_object_h( $tasks );
//return the sanitized object.
echo json_encode( $sanitized_tasks );
// return redirect( '/tasks/' . $project_id );
} else {
echo "failed";
return;
}//end if
}//end store
JavaScript:
function postData( form, url ) {
var returnData;
console.log("form data " + form.serialize());
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type:"POST",
data: form.serialize(),
success:function(data){
console.log(data);
},error:function(data){
console.log(data);
}
}); //end of ajax
return returnData;
}//end postData
HTML in the head:
<meta name="csrf-token" content="{{ csrf_token() }}">
I have just created a library class in laravel.
class Message {
public static $data = array();
public function __construct() {
// If session has flash data then set it to the data property
if (Session::has('_messages')) {
self::$data = Session::flash('_messages');
}
}
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}
I can use this class in my views calling Message::get(). In the controllers, I can set the message as Message::set('info', 'success message here.'); and it works perfectly fine.
However, I can not use this class for flash messages redirects using Message::set('info', 'success message here.', true). Any idea, whats wrong in this code?
First problem is the constructor function is not called when using the above get and set methods, with minor modification the code is now working. :)
class Message {
public static $data = array();
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// Check the session if message is available in session
if (Session::has('_messages')) {
self::$data = Session::get('_messages');
}
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}
I am not able to load models to the extended My_Router class in codeigniter. Below is my code:
class MY_Router extends CI_Router {
function MY_Router()
{
parent::CI_Router();
}
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Let's check if there are category segments
$category_routes = $this->category_routing($segments);
if($category_routes !== FALSE)
{
return $category_routes;
}
$user_routes = $this->user_routing($segments);
if($user_routes != FALSE)
{
return $user_routes;
}
show_404($segments[0]);
}
function category_routing($segments)
{
$this->load->model('category_model');
if($this->category_model->category_exist($segments[0]))
{
//if only category
if(count($segments)==1)
{
return array('category', 'category_browse', $segments[0]);
}
//category pagination
if(count($segments)==2 and is_numeric($segments[1]))
{
return array('category','category_browse', $segments[0], $segments[1]);
}
//category upcoming
if(count($segments)==2 and $segments[1] == 'upcoming')
{
return array('category','upcoming', $segments[0]);
}
//category upcoming pagination
if(count($segments)==3 and $segments[1] == 'upcoming' and is_numeric($segments[3]))
{
return array('category','upcoming', $segments[0], $segments[3]);
}
//category top
if(count($segments)==3 and $segments[1] == 'top')
{
return array('category','top', $segments[0], $segments[2]);
}
//category top pagination
if(count($segments)==4 and $segments[1] == 'top' and is_numeric($segments[3]))
{
return array('category','top', $segments[0], $segments[3]);
}
}
return FALSE;
}
function user_routing($segments)
{
$this->load->model('dx_auth/users', 'user_model');
if($this->user_model->check_username($segments[0]))
{
//only profile
if(count($segments)==1)
{
return array('user','profile',$segments[0]);
}
//all friends
if(count($segments)==2 and $segment[1]=='allfriends')
{
return array('user','allfriends',$segments[0]);
}
//all subscribers
if(count($segments)==2 and $segment[1]=='allsubscribers')
{
return array('user','allsubscribers',$segments[0]);
}
//all subscription
if(count($segments)==2 and $segment[1]=='allsubscriptions')
{
return array('user','allsubscriptions',$segments[0]);
}
}
return FALSE;
}
}
I have tried loading the models by using get_instance function provided by codeigniter but seems like it doesnot work. All i need is load the models in extended system library.
There is no access to the CodeIgniter super-global until CI_Base has been called which is extended by Controller. The Controller class then loads the Loader library:
// In PHP 5 the Loader class is run as a discreet
// class. In PHP 4 it extends the Controller
if (floor(phpversion()) >= 5)
{
$this->load =& load_class('Loader');
$this->load->_ci_autoloader();
}
The Router is loaded very on (have a look in system/codeigniter/CodeIgniter.php to see exactly when, on line 99) so has barely anything available.
You can use load_class('Whatever'); to load classes in a different order, but this can really screw with things if you are not careful, and you still wont have access to the database drivers.
Basically, you can't do it this way. You would need to try and directly work with the database library or use native MySQL bindings to access your data.
Here is what i did and it worked..Thanks phil for suggestion.
class MY_Router extends CI_Router {
function MY_Router()
{
parent::CI_Router();
}
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Let's check if there are category segments
$category_routes = $this->category_routing($segments);
if($category_routes !== FALSE)
{
return $category_routes;
}
$user_routes = $this->user_routing($segments);
if($user_routes !== FALSE)
{
return $user_routes;
}
show_404($segments[0]);
}
function category_routing($segments)
{
if($this->check_category_exist($segments[0]))
{
//if only category
if(count($segments)==1)
{
return array('category', 'category_browse', $segments[0]);
}
//category pagination
if(count($segments)==2 and is_numeric($segments[1]))
{
return array('category','category_browse', $segments[0], $segments[1]);
}
//category upcoming
if(count($segments)==2 and $segments[1] == 'upcoming')
{
return array('category','upcoming', $segments[0]);
}
//category upcoming pagination
if(count($segments)==3 and $segments[1] == 'upcoming' and is_numeric($segments[3]))
{
return array('category','upcoming', $segments[0], $segments[3]);
}
//category top
if(count($segments)==3 and $segments[1] == 'top')
{
return array('category','top', $segments[0], $segments[2]);
}
//category top pagination
if(count($segments)==4 and $segments[1] == 'top' and is_numeric($segments[3]))
{
return array('category','top', $segments[0], $segments[3]);
}
}
return FALSE;
}
function check_category_exist($cat_name)
{
//connect to database and find the category
include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
mysql_select_db($db['default']['database'],$conn);
$sql = sprintf("SELECT COUNT(id) as count FROM categories WHERE permalink = '%s'", mysql_real_escape_string($cat_name));
$query = mysql_query($sql);
$row = mysql_fetch_object($query);
mysql_close($conn);
if($row->count)
{
return TRUE;
}
return FALSE;
}
function user_routing($segments)
{
if($this->check_username_exist($segments[0]))
{
//only profile
if(count($segments)==1)
{
return array('user','profile',$segments[0]);
}
//all friends
if(count($segments)==2 and $segments[1]=='allfriends')
{
return array('user','allfriends',$segments[0]);
}
//all subscribers
if(count($segments)==2 and $segments[1]=='allsubscribers')
{
return array('user','allsubscribers',$segments[0]);
}
//all subscription
if(count($segments)==2 and $segments[1]=='allsubscriptions')
{
return array('user','allsubscriptions',$segments[0]);
}
}
return FALSE;
}
function check_username_exist($username)
{
//connect to database and find the category
include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
mysql_select_db($db['default']['database'],$conn);
$sql = sprintf("SELECT COUNT(id) as count FROM users WHERE username = '%s'", mysql_real_escape_string($username));
$query = mysql_query($sql);
$row = mysql_fetch_object($query);
mysql_close($conn);
if($row->count)
{
return TRUE;
}
return FALSE;
}
}
The following code will solve your problem too and will make your coding lot easier and flexible.
require_once( BASEPATH . 'database/DB' . EXT );
$db = & DB();
$query = $db->query("select ...");
$results = $query->result();
When using the base CodeIgniter class in external Libraries you have to invoke it again like this:
// load it
$CI =& get_instance();
$CI->load->model('model_name');
//use it
$CI->model_name->method()
Hope that helps