Reference- what is wrong with my codeigniter code - php

hello everyone i write a codeigniter function to return data fro database
this is my function
public function get_total_results($filtering = false)
{
if ($filtering) {
$this->get_filtering();
}
foreach ($this->joins as $val) {
$this->ci->db->join($val[0], $val[1], $val[2]);
}
foreach ($this->where as $val) {
$this->ci->db->where($val[0], $val[1], $val[2]);
}
foreach ($this->or_where as $val) {
$this->ci->db->or_where($val[0], $val[1], $val[2]);
}
foreach ($this->group_by as $val) {
$this->ci->db->group_by($val);
}
foreach ($this->like as $val) {
$this->ci->db->like($val[0], $val[1], $val[2]);
}
if (strlen($this->distinct) > 0) {
$this->ci->db->distinct($this->distinct);
$this->ci->db->select($this->columns);
}
$query = $this->ci->db->get($this->table, null, null, false);
return $query->num_rows();
}
but i get an error of
An uncaught Exception was encountered
Type: Error
Message: Call to a member function num_rows() on boolean
in line of return $query->num_rows();
i don't know what is wrong with my code that i got this error so i know the error in last line in returning result any suggestion or idea

The problem is that the line
$query = $this->ci->db->get($this->table, null, null, false);
// Note: all you really need is $this->ci->db->get($this->table);
It is assigning the value false to $query. That usually happens when Query Builder creates a SQL statement that does not make sense - it happens.
You can see what Query Builder creates this way
// comment out the get() call
// $this->ci->db->get($this->table);
// run this instead
$sql = $this->db->get_compiled_select($this->table);
echo $sql;
// remove the comments once you see where the problem is
//return $query->num_rows();
You will probably be able to see where the SQL statement syntax is wrong and adjust your earlier code accordingly.
You might want to add a check of the get() return to your logic, e.g.
$query = $this->ci->db->get($this->table);
// Is $query truthy? (not false, null, etc)
if(! empty($query))
{
return $query->num_rows();
}

get() method of codeigniter have syntax like:
get([$table = ''[, $limit = NULL[, $offset = NULL]]])
Parameters: $table (string) – The table to query $limit (int) – The
LIMIT clause $offset (int) – The OFFSET clause
Returns: CI_DB_result instance (method chaining)
Return type: CI_DB_result
You have passed more than three parameters. So, Please check the parameters. It may resolve your problem.
Refer this for more information.

Related

Call to a member function isCollection() on null

I, using the Graphaware Neo4j-php-OGM. I would like to access the 2nd level relationship. I can't seen to get it to work. What am i doing wrong?
I'm trying to execute the following:
public function allowToContinue($userUuid, $permissionUuid)
{
$userRepo = $this->entityManager->getRepository(User::class);
$permRoleRepo = $this->entityManager->getRepository(PermRole::class);
$permissionRepo = $this->entityManager->getRepository(Permission::class);
$user = $userRepo->findOneBy(['uuid' => $userUuid]);
$permission = $permissionRepo->findOneBy(['uuid' => $permissionUuid]);
$allowed = false;
foreach ($user->getPermrole() as $userRole)
{
var_dump($userRole);
$role = $permRoleRepo->findOneBy(['uuid' => $userRole->getUuid()]);
var_dump($role);
foreach ($role->getPermissions() as $perm)
{
var_dump($perm->getUuid());
if($perm->getUuid() === $permissionUuid){
$allowed = true;
}
}
}
return $allowed;
}
Stacktrace:
Error:
Call to a member function isCollection() on null
at vendor/graphaware/neo4j-php-ogm/src/Hydrator/EntityHydrator.php:107
at GraphAware\Neo4j\OGM\Hydrator\EntityHydrator->hydrateSimpleRelationshipCollection('permissions', object(Result), object(neo4j_ogm_proxy_App_Entity_Generic_PermRole))
(vendor/graphaware/neo4j-php-ogm/src/Persisters/BasicEntityPersister.php:104)
at GraphAware\Neo4j\OGM\Persisters\BasicEntityPersister->getSimpleRelationshipCollection('permissions', object(neo4j_ogm_proxy_App_Entity_Generic_PermRole))
(vendor/graphaware/neo4j-php-ogm/src/Proxy/NodeCollectionInitializer.php:22)
at GraphAware\Neo4j\OGM\Proxy\NodeCollectionInitializer->initialize(object(Node), object(neo4j_ogm_proxy_App_Entity_Generic_PermRole))
(vendor/graphaware/neo4j-php-ogm/src/Proxy/LazyCollection.php:52)
at GraphAware\Neo4j\OGM\Proxy\LazyCollection->doInitialize()
(vendor/doctrine/collections/lib/Doctrine/Common/Collections/AbstractLazyCollection.php:332)
at Doctrine\Common\Collections\AbstractLazyCollection->initialize()
(vendor/doctrine/collections/lib/Doctrine/Common/Collections/AbstractLazyCollection.php:274)
at Doctrine\Common\Collections\AbstractLazyCollection->getIterator()
(src/Security/RoleChecker.php:45)
at App\Security\RoleChecker->allowToContinue('8d88d920-5ab0-11e8-a371-001c42dff143', 'd93370b0-585d-11e8-a371-001c42dff143')
(src/Controller/Generic/UserController.php:146)
at App\Controller\Generic\UserController->destroy('c34f1380-5ab5-11e8-a371-001c42dff143')
(vendor/symfony/http-kernel/HttpKernel.php:149)
at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
(vendor/symfony/http-kernel/HttpKernel.php:66)
at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
(vendor/symfony/http-kernel/Kernel.php:188)
at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
(public/index.php:37)
It throws the error on the 2nd foreach loop on line:
foreach ($role->getPermissions() as $perm)
It's strange, working the first time correctly and not the 2nd time. Also after fetching the object again to be sure. Without this it throws the exact same notice.
Thanks in advance!
All code is at github: https://github.com/djkevino/Support4Neo
Honestly, pretty confused by this code. The var_dump() die() stuff in destroy()... Also, took me a while to realize we are talking about code in the library, not your code that interacts with this library.
Can you avoid the issue like so?
//add this next line
if (!is_iterable($user->getPermrole())) continue;
foreach ($role->getPermissions() as $perm)
If you are not on PHP version 7.1 or greater you could simply check if the returned value is_null or test for instance of \Traversable and is_array...
is_array($foo) || (is_object($foo) && ($foo instanceof \Traversable ));
As stated in my comment, not sure if that role having no "permissions" is considered a valid state or not.
It looks like $role->getPermissions() can return a null result. So, make sure the result is not null before executing the inner foreach loop.
Since you seem to be testing if any of the user's roles has the desired permission, you do not need the $allowed variable at all. The inner foreach loop can just immediately return true once a match is found, avoiding unnecessary processing.
That is, try this:
public function allowToContinue($userUuid, $permissionUuid) {
$userRepo = $this->entityManager->getRepository(User::class);
$permRoleRepo = $this->entityManager->getRepository(PermRole::class);
$permissionRepo = $this->entityManager->getRepository(Permission::class);
$user = $userRepo->findOneBy(['uuid' => $userUuid]);
$permission = $permissionRepo->findOneBy(['uuid' => $permissionUuid]);
foreach ($user->getPermrole() as $userRole) {
var_dump($userRole);
$role = $permRoleRepo->findOneBy(['uuid' => $userRole->getUuid()]);
var_dump($role);
$rolePerms = $role->getPermissions();
if (!is_null($rolePerms)) {
foreach ($rolePerms as $perm) {
var_dump($perm->getUuid());
if ($perm->getUuid() === $permissionUuid) {
return true;
}
}
}
}
return false;
}

Dynamic query ORM Laravel 4.2

Alright I have a GeneralModel written in CodeIgniter and a friend asked me if I could convert it into Laravel 4.2 for him. I was working on this and I think I have most of it correct but I am getting stuck at the select statement.
In CodeIgniter I have the following:
public function getData($table, $multiple = 1, $field = FALSE, $val = FALSE){
if($field != FALSE){
// WHERE in case of FIELD / VAL :)
$this->db->where($field, $val);
}
$query = $this->db->get($table);
if($multiple == 1){
// Multiple rows
return $query->result_array();
} else {
// One row
return $query->row_array();
}
}
Does anyone here knows how I can convert this function into Laravel 4.2 syntax?
I currently have:
public function getData($table, $multiple = 1, $field = FALSE, $val = FALSE){
$result = DB::table($table);
}
I got stuck pretty quickly since I have no idea how I can achieve the same in Laravel 4.2 with splitting up the sections of the query like I did with CodeIgniter.
You can chain methods in the same way:
public function getData($table, $multiple = 1, $field = FALSE, $val = FALSE)
{
$query = DB::table($table);
if ($field != FALSE) {
// WHERE in case of FIELD / VAL :)
$query->where($field, $val);
}
if ($multiple)
return $query->get();
else
return $query->first();
}
Laravel is similar in that you can use the Fluent Query Builder to build your queries in multiple stages prior to actually making the query. Once you know this, the translation is pretty straightforward:
public function getData($table, $multiple = 1, $field = FALSE, $val = FALSE)
{
$query = DB::table($table);
if($field){
// WHERE in case of FIELD / VAL :)
$query = $query->where($field, $val);
}
if($multiple) {
return $query->get();
}
return $query->first();
}
I don't think it's really good practice relying on Fluent though inside of an Eloquent model, but there are cases where that can't be helped. If the current objective is to convert the project to Laravel, there's probably calling code relying on the fact that this method exists. Converting the function to use Eloquent rather than Fluent will change the function's signature and cause other parts of the code to break, but it would look like this:
public function getData($multiple = true, $field = false, $val = false)
{
$query = $this;
if($field) {
$query = $query->where($field, $val);
}
if($multiple) {
return $query->get();
}
return $query->first();
}
The calling code itself can be modified to do the exact same function in Laravel like this:
// Instead of...
$result = $model->getData(1, 'field', 'value');
// You can do this:
$result = $model->where('field', 'value')->get();
// Or this if you'd rather not have multiple:
$result = $model->where('field', 'value')->first();
Using this function inside Eloquent (IMHO) in the long run doesn't really save you much, and instead is mostly just clutter.

PHP Error: Cannot use a scalar value as an array... However

I'm currently working with the medoo.php framework, and although I would normally use their ticket area on github, it appears that no one actually uses that... so...
At any rate, when I'm running one of my files which uses "require" to call the framework, I get the following error:
Warning: Cannot use a scalar value as an array in /home/..../public_html/projects/friendcodes/medoo.min.php on line 759
However, when I inspect the code (the below is lines 752 to 764), I see that it is in fact supposed to check if $where is not set, and if it isn't, make it an array - however this php error begs to differ.
I'm guessing that $where is being set as a variable somewhere else, that's not an array, but there are over 100 occurrences of the variable in the framework, and 830 lines of code, which you probably don't want to see. (Let me know in a comment and I'll add it - again, this is directly from medoo's most two recent updates/releases.)
public function get($table, $columns, $where = null)
{
if (!isset($where))
{
$where = array();
}
$where['LIMIT'] = 1;
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}
My main question is - How do I rectify this problem without breaking something in this framework which is extremely complex (for my level, at any rate)
Update: How silly of me! I found the problem. Just as people suggested, I was calling $where wrong.
I was calling it with:
$accountinfo = $database->get('xf_user_field_value', ['field_value'], 1);
Instead of
$accountinfo = $database->get('xf_user_field_value', ['field_value'], ["user_id"=>1]);
(Where the third arg is $where) Thanks for the help guys!
Right, first things first, we need to find out what is calling get that shouldn't be. WHICH IS THE ENTIRE PROBLEM. The problem isn't the function itself, the problem is something is calling it using an argument for $where which isn't an array. Changing a library to fix one faulty call is ridiculous.
Step 1: Temporarily edit the get function to include a print_r of the $where variable.
public function get($table, $columns, $where = null)
{
if(isset($where)) print_r($where);
if (!isset($where))
{
$where = array();
}
$where['LIMIT'] = 1;
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}
This will show us before the error prints the value of $where, which will help you find the malformed get call.
If this fails, try using PHP's built-in backtrace to try to find the issue:
public function get($table, $columns, $where = null)
{
if(isset($where)) print_r(debug_backtrace());
if (!isset($where))
{
$where = array();
}
$where['LIMIT'] = 1;
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}
The ->get() method is not called properly.
Cannot use a scalar value as an array
That warning is shown if $where is either true, a numeric value or a resource. Valid method calls include:
->get('table', '*')
->get('table', '*', array('WHERE' => 'foo = "bar"'))
Check the manual and fix your code.
EDIT 3: try moving $where['LIMIT'] = 1; inside of the isset statement, since you wouldn't want to pass LIMIT 1 to the query constructor if $where is passed by reference.
DISCLAIMER I have no knowledge of the medoo framework.
public function get($table, $columns, $where = null)
{
if (is_null($where))
{
$where = array('LIMIT'=>1);
}
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}

How make a Dynamic bindValue()?

Okay I have a function called sendQuery which sends your query.
I know how to do it with BindParams, but I can't really think of a way to make it work with bind values inside a execute.
This is the code:
public function sendQuery($query, array $value, $do_fetch)
{
$query_process = $this->db->prepare($query);
if(!$query_process->execute($binds))
{
throw new excpetion ("An error has occured!");
}
$this->insert = $this->db->lastInsertId();
$this->row_count = $query_process->rowCount();
if($fetch == true)
{
return $query_process->fetchAll();
}
}
As you see, it executes with $binds,
Works like (WHERE user = ?), but I want to send queries like this:
(WHERE user = :user) instead of a ' ? ', and multiple of them.
How do I do so?
You have to do exactly the same.
Just get rid of useless code and use consistent variable naming
public function sendQuery($query, array $binds, $do_fetch)
{
$stm = $this->db->prepare($query);
$stm->execute($binds);
$this->insert = $this->db->lastInsertId();
$this->row_count = $stm->rowCount();
if($do_fetch)
{
return $stm->fetchAll();
}
}
$sql = "SELECT * FROM t WHERE c1=:name AND c2=:age";
$param = array ("name" => $name,"age" => $age);
$data = $db->sendQuery($sql, $data, 1);
However, instead of just single function I would create a set of them:
query() to run non-select queries
getOne() preforms select and returns scalar value
getRow() returns a row
getAll returns all rows
it could be extremely handy

Static method, Zend_View error

I have a static method 'findAll' on a model which basically gets all rows with certain criteria. This method works fine and I can call it using:
$m::findAll();
Where $m is the model name as a variable. I can output this and it returns correct results. However, when assigning this to a variable in the Zend_View object, as:
$this->view->viewvariable = $m::findAll();
I get the error:
Zend_Db_Table_Exception: Too many
columns for the primary key
Any ideas why?
Find all function:
final public static function findAll($where = false, array $options = array()) {
$object = new static();
if (!empty($options)) $options = array_merge($object->options, $options);
else $options = $object->options;
$run = $object->buildDefaultSelect($where, $options);
$rows = $run->fetchAll();
if ($options['asObject'] == true) {
$result = array();
foreach ($rows as $r) {
$class = new static();
$class->setInfo($r);
$result[] = $class;
}
return $result;
} else {
if (count($rows) > 0) return $rows;
else return array();
}
}
Note: This function works fine everywhere apart from when assigning to a view variable. If I run the below (not assigning it to a view variable), it shows the correct array data.
var_dump($m::findAll($module['where'], $module['options']));
exit;
In my view (I have replaced the actual name with viewvariable for the sake of this post):
<?php foreach($this->viewvariable as $item) { ?>
//Do some echoing of data in $item
//Close foreach
I doubt the issue is with Zend_View. It's hard to tell without seeing your code, but my guess is that findAll() is using the Zend_Table_Db find() function incorrectly.
To my knowledge, the only place that throws that exception is the find() function on Zend_Db_Table_Abstract.
Perhaps, inside the findAll() function (or in a function it calls) you're doing one of these:
$zendDbTable->find(1,2) //is looking for a compound key
$zendDbTable->find(array(1,2)) //is looking for two rows
When you really want the opposite.

Categories