Problems storing image url in database on upload (CodeIgniter) - mysql

This is widely discussed topic:how to save image url in database on upload?
I have read them but still can not understand why my controller is not working. I followed CodeIgniters documentation on uploading files and created controler that uploads file in desired directory, so far so good. I now want to save image url in database on upload. I modified code from this question but I have multiple errors that I can not get around.
1.
Message: Illegal string offset 'file_name'
Filename: controllers/Upload.php
Line Number: 36
2.Message: Undefined property: Upload::$db
Filename: controllers/Upload.php
Line Number: 37
3.Message: Call to a member function insert() on null
Filename: controllers/Upload.php
Line Number: 37
Here is my controller(I have test table puzz with two fields - auto increment primary key id and image_url):
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = $this->upload->data();
$file_array = $this->upload->data('file_name');
$image['image_url'] = $file_array['file_name'];
$this->db->insert('puzz', $image);
$this->load->view('upload_success', $data);
}
}
}
?>
Will appreciate if someone could point to wrongs in my code!

add this before using insert
$this->load->database();
OR change constructor
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->database();
}
OR change in autoload.php
$autoload['libraries'] = array('database');
AND change this code block to
$data = $this->upload->data();
$image['image_url'] = $data['file_name'];
$this->db->insert('puzz', $image);
$this->load->view('upload_success', $data);

Related

Conflicting Laravel controllers- one can call method the other gives non-static error

I've taken over the code from another developer, and I'm quite confused and stuck: one controller I can call the class method CLASSS::method perfectly OK. the other Controller has a copy of the orginal code and modified. On the second one, I get the "non-static method" error.
Call Chain:
Controller->Class->filtered results->Controller response
1A) (Working) Conttroller
<?php
namespace App\Http\Controllers\V1;
use App\Site as SiteClass;
use Facades\App\Site;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\{
Http\Controllers\Controller,
Http\Requests\SiteRequest,
Helper\ResourceTrait,
Assets,
Alerts,
Licensee,
Permits,
LandOwner,
Utility
};
use Illuminate\Support\Collection;
class SiteController extends Controller
{
private $obj;
public function __construct()
{
$this->obj = new SiteClass();
}
public function index(Request $request)
{
try
{
$data = Site::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
);
...removed some extra code that's not relevant ...
return response($data);
}
catch(\Exception $e)
{
Log::info('Create exception from here?' . $e);
return response(array('error'=>$e->getMessage()),422);
}
} // index
....
}
1B) (Working) Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Site extends BaseModel
{
protected $table = 'sites';
protected $fillable = [
"status","structureType","siteId","name","coverage","address","postCode", "subdistrict", "district", "region", "state", "country", "localCouncil", "latitude", "longitude", "dimensions",
"siteHandover", "startBilling", "utilityBillAcct", "utilityBillingAddress", "renewalTerm",
"capex", "opex", "siteManager", "siteManagerPhone", "siteManagerEmail", "siteOwnerManager", "siteOwnerManagerPhone", "siteOwnerManagerEmail"
];
...
// Working Static method call.
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
->orWhere($this->table.'.status','=',$search)
->orWhere($this->table.'.siteId','like','%'.$search.'%')
->orWhere($this->table.'.address','like','%'.$search.'%')
->orWhere($this->table.'.subdistrict','like','%'.$search.'%')
->orWhere($this->table.'.district','like','%'.$search.'%')
->orWhere($this->table.'.region','like','%'.$search.'%')
->orWhere($this->table.'.state','like','%'.$search.'%')
->orWhere($this->table.'.country','like','%'.$search.'%')
->orWhere($this->table.'.localCouncil','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('siteId','desc');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
2A) (Failing) Controller
<?php
namespace App\Http\Controllers\V1;
use App\{
Http\Controllers\Controller,
Helper\ResourceTrait,
Http\Requests\OrganisationRequest,
Organisation
};
use Illuminate\{
Http\Request,
Support\Facades\Config,
Support\Facades\Log
};
class OrganisationController extends Controller
{
private $org;
public function __construct()
{
$this->org = new Organisation();
}
public function index(Request $request)
{
try
{
//WORKAROUND: $this->org->... works
$data = Organisation::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
); // FAILS with non-static method call error
return response($data);
}
catch(\Exception $e)
{
return response(array('error'=>$e->getMessage()),422);
}
} // index
}
...
2B) Failing Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Organisation extends BaseModel
{
protected $table = 'organisation';
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('name');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
To my untutored eye, they look identical, yet one works and the other doesn't. Apologies in advance for the volume of code, but I don't know which parts are affecting what. I suspect it's somethng to do with an imported class, but I'm lost frankly :-D
Site has a Facade while Organisation does not.
Facades (from the docs) provide a "static" interface to classes that are available in the application's service container.

Laravel saves child record, but sets foreign key to null

This has got to be a simple fix, as I have done this many times before. But as it stands I am completely stumped. I use the following code to save a parent object Unknown_Tag and its many children.
Method:
public function saveUnknown(Request $request)
{
$url = $request->url;
$tag = new Unknown_Tag();
$tag->url = $url;
$protocol =
substr($url, 0, strpos($url, ':'));
$tag->protocol = $protocol;
$domain =
parse_url($url, PHP_URL_HOST);
$tag->domain = $domain;
$tag->save();
//get the path
$Path = parse_url($url, PHP_URL_PATH);
if ($Path) {
$splitPath = substr($Path, 1);
$paths = explode('/', $splitPath);
foreach ($paths as $p) {
$path = new Path();
$path->path = $p;
$tag->Paths()->save($path);
}
}
//get Queries
$splitQuery = parse_url($url, PHP_URL_QUERY);
if ($splitQuery) {
$queries = explode('&', $splitQuery);
foreach ($queries as $q) {
$query = new Query();
$q = substr($q, 0, strpos($q, '='));
IF (SUBSTR($q, -1) != ' ') {
$q .= ' ';
}
$query->var = $q;
$value = $q = preg_replace('/^[^=]*:/', '', $q);
$query->value = $value;
$tag->Queries()->save($query);
}
}
}
The Parent Object
class Unknown_Tag extends Model
{
protected $table = 'unknown_tags';
public $timestamps = false;
public function Paths()
{
return $this->hasMany('App\Path', 'tag_id', 'ID');
}
public function Queries()
{
return $this->hasMany('App\Query', 'tag_id', 'ID');
}
}
The Child objects
class Query extends Model
{
protected $table = 'queries';
public $timestamps = false;
public function Tag()
{
return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
}
}
class Path extends Model
{
protected $table = 'paths';
public $timestamps = false;
public function Tag()
{
return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
}
}
When I run all this via a post request, The Parent and all the children are saved properly, but all the child objects have a foreign key that is set to null. If I manually change the foreign key to what it should be, everything works just fine, so I am fairly sure this is not a problem with my database. Can anyone see the obvious that I am missing here?
EDIT:Just to be clear, this returns no errors
If anyone ever sees this, laravel assumes the default primary key is 'id'. I had set mine to 'ID', so I had to let laravel know by using
protected $primaryKey = 'ID';
in my Unknown_tag definition

A circular reference has been detected (configured limit: 1) Serializer SYMFONY [duplicate]

I am using Doctrine 2 and Zend framework since a few days.
I am generating my entities across yaml files.
Now I met an issue to convert my entities Doctrine into Json format (in order to use it through AJAX).
Here is the code used :
$doctrineobject = $this->entityManager->getRepository('\Entity\MasterProduct')->find($this->_request->id);
$serializer = new \Symfony\Component\Serializer\Serializer(array(new Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer()), array('json' => new Symfony\Component\Serializer\Encoder\JsonEncoder()));
$reports = $serializer->serialize($doctrineobject, 'json');
below is the return I get :
Fatal error: Maximum function nesting level of '100' reached, aborting! in /Users/Sites/library/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php on line 185
the issue seems to be the same than here :
http://comments.gmane.org/gmane.comp.php.symfony.symfony2/2659
but there is not proper solution proposed.
Any idea how can I do it ?
Cheers
I solved the same problem by writing my own GetSetNormalizer my class. Defined static variable in a class for branching
class LimitedRecursiveGetSetMethodNormalizer extends GetSetMethodNormalizer
{
public static $limit=2;
/**
* {#inheritdoc}
*/
public function normalize($object, $format = null)
{
$reflectionObject = new \ReflectionObject($object);
$reflectionMethods = $reflectionObject->getMethods(\ReflectionMethod::IS_PUBLIC);
$attributes = array();
foreach ($reflectionMethods as $method) {
if ($this->isGetMethod($method)) {
$attributeName = strtolower(substr($method->name, 3));
$attributeValue = $method->invoke($object);
if (null !== $attributeValue && !is_scalar($attributeValue) && LimitedRecursiveGetSetMethodNormalizer::$limit>0) {
LimitedRecursiveGetSetMethodNormalizer::$limit--;
$attributeValue = $this->serializer->normalize($attributeValue, $format);
LimitedRecursiveGetSetMethodNormalizer::$limit++;
}
$attributes[$attributeName] = $attributeValue;
}
}
return $attributes;
}
/**
* Checks if a method's name is get.* and can be called without parameters.
*
* #param ReflectionMethod $method the method to check
* #return Boolean whether the method is a getter.
*/
private function isGetMethod(\ReflectionMethod $method)
{
return (
0 === strpos($method->name, 'get') &&
3 < strlen($method->name) &&
0 === $method->getNumberOfRequiredParameters()
);
}
}
And usage
LimitedRecursiveGetSetMethodNormalizer::$limit=3;
$serializer = new Serializer(array(new LimitedRecursiveGetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$response =new Response($serializer->serialize($YOUR_OBJECT,'json'));
JMSSerializerBundle seems to handle circular references fine.

Codeigniter Select JSON, Insert JSON

I have very simple users database: user_id, user_name, user_email
My model this:
class Users extends CI_Model {
private $table;
private $table_fields;
private $table_fields_join;
function __construct() {
parent::__construct();
$this->table = 'users';
$this->table_fields = array(
$this->table.'.user_id',
$this->table.'.user_name',
$this->table.'.user_email'
);
$this->table_fields_join = array();
}
function select(){
$this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));
$this->db->from($this->table);
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result();
} else {
return false;
}
}
function insert($data) {
$data = array(
'user_name' => $data['user_name'],
'user_email' => $data['user_email']
);
$this->db->insert($this->table, $data);
}
My controller this:
class Users extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('users');
}
public function select(){
$data['query'] = $this->users->select();
$data = json_encode($data['query']);
echo $data;
}
public function insert($json){
$data = json_decode($json);
$this->users->insert($data);
}
}
And this is my routing.php:
$route['default_controller'] = 'Welcome';
$route['users'] = 'users/select';
$route['users/insert/:(any)'] = 'users/insert';
I would like that 127.0.0.1/users/select give json.
Example: [{"user_name":"user1","user_email":"user#user.de"}]
This JSON insert my table: 127.0.0.1/users/insert/[{"user_name":"user1","user_email":"user#user.de"}]
But my code is not working. :-(
You want to return json object in response, so it's required to set json type in response header. As given here
public function select(){
$data['query'] = $this->users->select();
$this->output
->set_content_type('application/json')
->set_output(json_encode($data['query']));
}
It is required to encode part as below for insert part. so you can use this generated url to call your insert.
site_url('usres/insert/'.urlencode('[{"user_name":"user1","user_email":"user#user.de"}]'));
your insert route should be as
$route['users/insert/:(any)'] = 'users/insert/$1';
your insert method should be updated as
public function insert($json){
$json = urldecode($json);
$data = json_decode($json);
$this->users->insert($data);
}
}

Fatal error: Call to a member function getPermissionKeyByHandle() on a non-object

Hello I get the following messages at my site www.csvc.nl
Fatal error: Call to a member function getPermissionKeyByHandle() on a non-object in /var/www/vhosts/csvc.nl/httpdocs/cms/updates/concrete5.6.0/concrete/core/models/permission/response.php on line 53
The PHP code is:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Model_PermissionResponse {
protected $object;
protected $allowedPermissions = array();
protected $customClassObjects = array();
protected $category;
static $cache = array();
public function setPermissionObject($object) {
$this->object = $object;
}
public function getPermissionObject() {
return $this->object;
}
public function setPermissionCategoryObject($category) {
$this->category = $category;
}
public function testForErrors() { }
public static function getResponse($object) {
$r = PermissionCache::getResponse($object);
if (is_object($r)) {
return $r;
}
$category = PermissionKeyCategory::getByHandle(Loader::helper('text')- >uncamelcase(get_class($object)));
if (!is_object($category) && $object instanceof Page) {
$category = PermissionKeyCategory::getByHandle('page');
}
$txt = Loader::helper('text');
$c1 = get_class($object) . 'PermissionResponse';
if (!class_exists($c1)) {
$c1 = 'PagePermissionResponse';
}
$pr = new $c1();
$pr->setPermissionObject($object);
$pr->setPermissionCategoryObject($category);
PermissionCache::addResponse($object, $pr);
return $pr;
}
public function validate($permission, $args = array()) {
$u = new User();
if ($u->isSuperUser()) {
return true;
}
$pk = $this->category->getPermissionKeyByHandle($permission);
if (!$pk) {
print t('Unable to get permission key for %s', $permission);
exit;
}
$pk->setPermissionObject($this->object);
return call_user_func_array(array($pk, 'validate'), $args);
}
public function __call($f, $a) {
$permission = substr($f, 3);
$permission = Loader::helper('text')->uncamelcase($permission);
return $this->validate($permission, $a);
}
}
Does anybody knows what the problem is?
I had a similar issue on an incomplete 5.6.0 upgrade.
Concrete 5 has a core upgrade troubleshooting guide
For me, I just had to do this on my site: http://example.com/index.php/tools/required/upgrade and use the upgrade button.
FYI, this added entries to PermissionKeyCategories and other tables (which existed, but were empty).