Codeigniter function_exists not working correctly - codeigniter

I am using php function_exists() function exist on my Welcome controller. But for some reason it keeps on throwing my show_error even though my slideshow function exists.
With in my foreach loop I get module function name from database which in the foreach loop is called $function = $module['code'];
Question is: How am I able to make sure function_exists checks
function exists correctly?
<?php
class Welcome extends CI_Controller {
public function index() {
$data['content_top'] = $this->content_top();
$this->load->view('home', $data);
}
public function content_top() {
$data['modules'] = array();
$modules = $this->get_module();
foreach ($modules as $module) {
$function = $module['code'];
if (function_exists($function)) {
$setting_info = array('test' => 'testing');
if ($setting_info) {
$data['modules'][] = $this->$function($setting_info);
}
} else {
show_error('This ' . $function . ' does not exist on ' . __CLASS__ . ' controller!');
}
}
return $this->load->view('content_top', $data, TRUE);
}
public function banner() {
}
public function slideshow($setting) {
$data['test'] = $setting['test'];
$this->load->view('module/slideshow', $data);
}
public function get_module() {
$query = $this->db->get('modules');
return $query->result_array();
}
}

function_exists() works on functions, but not class methods - these are different things. What you want is method_exists():
method_exists($this, $function);

Related

Try to use the codeigniter's file upload library as a general function from Helpers

Can anybody help as I am trying to use the codeigniter's upload library from the helpers folder but I keep getting the same error that I am not selecting an image to upload? Has any body tried this before?
class FileUpload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'file_uploading'));
$this->load->library('form_validation', 'upload');
}
public function index() {
$data = array('title' => 'File Upload');
$this->load->view('fileupload', $data);
}
public function doUpload() {
$submit = $this->input->post('submit');
if ( ! isset($submit)) {
echo "Form not submitted correctly";
} else { // Call the helper
if (isset($_FILES['image']['name'])) {
$result = doUpload($_FILES['image']);
if ($result) {
var_dump($result);
} else {
var_dump($result);
}
}
}
}
}
The Helper Function
<?php
function doUpload($param) {
$CI = &get_instance();
$CI->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|png|jpg|jpeg|png';
$config['file_name'] = date('YmdHms' . '_' . rand(1, 999999));
$CI->upload->initialize($config);
if ($CI->upload->do_upload($param['name'])) {
$uploaded = $CI->upload->data();
return $uploaded;
} else {
$uploaded = array('error' => $CI->upload->display_errors());
return $uploaded;
}
}
There are some minor mistakes in your code, please fix it as below,
$result = doUpload($_FILES['image']);
here you should pass the form field name, as per your code image is the name of file input.
so your code should be like
$result = doUpload('image');
then, inside the function doUpload you should update the code
from
$CI->upload->do_upload($param['name'])
to
$CI->upload->do_upload($param)
because Name of the form field should be pass to the do_upload function to make successful file upload.
NOTE
Make sure you added the enctype="multipart/form-data" in the form
element

Laravel 5.6 Many To Many Polymorphic Relations Insert Not Work

I'm use laravel 5.6 on this project. Categories value not recorded 'categorizables' pivot table. I check with f12 or bug but I do not get any errors. all of them ok but not recorded pivot table. Where I have
been mistake.
My Blog project sql structure is below
--blogs
id
title
description
...
-- categorizables
category_id
categorizable_id
categorizable_type
Below code belong to Category.php Model
class Category extends Model
{
protected $primaryKey='category_id';
public function blogs(){
return $this->morphedByMany('App\Blog', 'categorizable', 'categorizables', 'category_id');
}
}
Above code belong to Blog.php
public function category($categories)
{
$categories = Blog::buildCatArray($categories);
foreach ($categories as $catName) {
$this->addOneCat($catName);
$this->load('categories');
}
return $this;
}
public function buildCatArray($categories): array
{
if (is_array($categories)) {
$array = $categories;
} elseif ($categories instanceof BaseCollection) {
$array = $this->buildCatArray($categories->all());
} elseif (is_string($categories)) {
$array = preg_split(
'#[' . preg_quote(',;', '#') . ']#',
$categories,
null,
PREG_SPLIT_NO_EMPTY
);
} else {
throw new \ErrorException(
__CLASS__ . '::' . __METHOD__ . ' expects parameter 1 to be string, array or Collection; ' .
gettype($categories) . ' given'
);
}
return array_filter(
array_map('trim', $array)
);
}
protected function addOneCat(string $catName)
{
$cat = Self::findOrCreate($catName);
$catKey = $cat->getKey();
if (!$this->cats->contains($catKey)) {
$this->categories()->attach($catKey);
}
}
public function find(string $catName)
{
return $this->Category::$catName->first();
}
public function findOrCreate(string $catName): Category
{
$cat = $this->find($catName);
if (!$cat) {
$cat = $this->Category::create(['name' => $catName]);
}
return $cat;
}
This my Blog Controller file store class
BlogController.php
public function store(Request $request)
{
$data = new Blog;
$data->title = $request->title;
$data->content = $request->content;
$tags = explode(',',$request->tag);
$categories = explode(',',$request->category);
$data->save();
$data->tag($tags);
$data->category($categories);
}
Best wishes

Laravel Passing Variable from a controller to another Controller

I'm trying to pass a variable from a controller to another controller I tried using
Redirect::to('dashboard/'.$ssid.'/')->with(compact('wname'))
but does not work any idea how can I achieve this?
here is my code
Route
Route::get('dashboard/{ssid}/', 'HomeController#showDash');
LoginController
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value):
$activated = $value['a_status'];
$wname = $value['wholename'];
endforeach;
if($activated == 1):
$red= Redirect::to('dashboard/'.$ssid.'/')->with(compact('wholename'));
else:
$red= View::make('login');
endif;
return $red;
}
}
HomeController
public function showDash($ssid,$wholename)
{
foreach ($wholename as $userVal):
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
endforeach;
return View::make('dashboard')->with(compact('fn'));
}
The error I'm having is that Missing argument 2 for HomeController::showDash() as per laravel's debugger..
Updated answer based on the comments:
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value){
$activated = $value['a_status'];
$wname = $value['wholename'];
}
if($activated == 1) {
Redirect::to('dashboard/'.$ssid.'/')->with(['wholename' => $wholename]);
}
return View::make('login');
}
public function showDash($ssid)
{
$wholename = (Session::has('wholename')) ? Session::get('wholename') : [];
foreach ($wholename as $userVal) {
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
}
return View::make('dashboard')->with(compact('fn'));
}
Everything else can stay as is.
Update: fixed erroneous space in 'whole name' (autocorrect did that, sorry).

select fails in custom model codeigniter 2

I have a problem with database select function, in my custom model. This is the code
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('inflector');
}
public function fetch($parameters = array(), $raw = FALSE)
{
$tablename = $this->getTableName();
$this->select_fields(FALSE == empty($parameters['fields']) ? $parameters['fields'] : FALSE);
unset($parameters['fields']);
if (FALSE == empty($parameters['limit'])) $limit = $parameters['limit'];
if (FALSE == empty($parameters['offset'])) $offset = $parameters['offset']; else $offset = 0;
unset($parameters['limit']);
unset($parameters['offset']);
if (FALSE == empty($limit))
{
$this->db->limit($limit, $offset);
}
$this->parseFilters($parameters);
$query = $this->db->get($tablename);
if ($query->num_rows() > 0)
{
if ($raw)
return $query;
$rows = $query->result();
$objects = array();
foreach ($rows as $row)
$objects[] = $this->hidrate($row);
return $objects;
}
else
{
return array();
}
}
protected function select_fields($fields)
{
if (TRUE == empty($fields))
{
$fields = "`" . $this->getTableName() . "`.*";
}
$this->db->select($fields);
}
public function fetchOne($parameters = array())
{
$parameters['limit'] = 1;
$list = $this->fetch($parameters);
if (FALSE == empty($list))
{
return reset($list);
}
else
{
return null;
}
}
Expecifict in $this->db->select($fields);
Fatal error: Call to a member function select() on a non-object
The model is a custom model and the applicacions model extends of this model. The question is why throws that error the database is correct.
I have a MY_loader create in codeginiter 1.7 and I try update to codeigniter 2
class MY_Loader extends CI_Loader
{
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
if ( substr($model, -4) == '_dao' )
{
return parent::model('dao/' . $model, $name, $db_conn);
}
parent::model( 'dao/' . $model . '_dao', $model, $db_conn);
include_once APPPATH . '/models/' . $model . EXT;
}
}
I don't know how update this model to codeigniter 2 and I believe this Loader generates error with my MY_Model
I'll try troubleshooting why does db return as a non-object.
I'd remove all code and start with a simple select(), if that works, I'll start adding code gradually and see where it breaks.
everything seems to be in order but first you'll need to see if the basic functionality exists.
so
1)remove all code, see if a basic select() works, if it doesn't, troubleshoot further.
2)if it does, keep adding code and see what breaks the select() statement.
3)keep adding code until you spot the issue.

Codeigniter database check

i am currently working on a project where users can save note snippets in there own little user area.
I was wondering how would i check if the id of an item exists for example if a user visits
http://mysite.com/view/1 and there is a note snippet of 1 it will display all the data relating to the id of one. Now if the user was to change the url to lets say 1000, that id doesnt exist and the view just errors.
i want to be able to redirect them back to a certain page with a error message "snippet does not exist" etc.
heres what i have so far ( i currently already have a conditional statement in here to check if the snippet is private, then if it is redirect back to /publicsnippets)
Controller:
class Publicsnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['public_snippets'] = $this->dashboard_model->public_snippets();
$this->load->view('dashboard/public_snippets', $this->data);
}
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}
}
Model:
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
public function delete_snippet($snippet_id)
{
$this->db->where('id', $snippet_id);
$this->db->delete('snippets');
}
}
View:
<h3>Description</h3>
<p><?php echo $snippet['description']; ?></p>
<h3>Tags</h3>
<p><?php echo $snippet['tags']; ?></p>
<h3>Date Submitted</h3>
<p><?php echo $snippet['date_submitted']; ?></p>
<h3>Snippet</h3></pre>
<pre class="prettyprint"><?php echo $snippet['code_snippet']; ?></pre>
You work is fine just add a check like this in your view method
Controller
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if($snippet){
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}else{
$this->session->set_flashdata('message', "<b style=\"color:red;\">snippet does not exist</b>");
redirect('/publicsnippets');
}
}
if no row is found in get_snippet method the $snippet will contain false or null
and the second block of condition will run.
In your model change get_snippet() to check for rows:
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
Then in your controller:
if ($snippet = $this->dashboard_model->get_snippet($snippet_id)) {
// code if snippet exists
} else {
// code if snippet doesn't exist
}
OR
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet) {
// etc...

Resources