Variable is an array but not countable? - php

I am upgrading our Codeigniter (v. 3.1.11) site from php 5.6 to php 7.2 (currently running on localhost on my Mac). Slowly I am finding all the instances of count() usage and correcting them. It is my understanding that an array is countable, but I seem to not be able to count arrays returned by Codeigniter's result_array() function after a database call....
the following section of my controller
$reviews = $this->reviews_model->review_details($productname);
echo "Variable is type: ".gettype($reviews);
if (count($reviews >=1)) {
$myreview=$reviews[0];
} else {
$myreview=0;
}
return $myreview;
calls this function in my model (note that I am echoing out the variable type just to be sure!)
function review_details($pagename) {
$r = false;
$sql = "select Reviews.*, ReviewItemLink.Item as Product, ReviewItemLink.* from Reviews LEFT JOIN ReviewItemLink ON Reviews.ReviewItemID=ReviewItemLink.ReviewItemID where pagename=? AND ReviewActive = 1 ORDER BY Date DESC";
$query = $this->db->query($sql, $pagename);
if ($query->num_rows() > 0):
$r = $query->result_array();
endif;
return $r;
}
And even though the variable is an array
Variable is type: array
I still get the by now, oh-so-familiar warning message:
Severity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: controllers/Software.php
Line Number: 1005
Backtrace:
File: /Users/juner/Sites/html/application/controllers/Software.php
Line: 1005
Function: _error_handler
File: /Users/juner/Sites/html/application/controllers/Software.php
Line: 75
Function: _get_my_review
File: /Users/juner/Sites/html/index.php
Line: 324
Function: require_once
Are there types of arrays that are NOT countable? Any suggestions/ideas would be most helpful!

This part is incorrect (typo?):
if (count($reviews >=1)) {
$myreview=$reviews[0];
} else {
$myreview=0;
}
You are passing a boolean to the count function. count($reviews >=1) turns to count(true); which is why you got your warning.
if (count($reviews >=1)) { should be if (count($reviews) >=1 ) {

Related

Message: Array to string conversion

I am trying to search product from the database and then display in view. But it showing me an error that is this...
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_active_rec.php
Line Number: 679
Here is the code of Controller
function search_prd()
{
$query = $this->input->post();
$this->load->model('prd/addprd');
$prd_search = $this->addprd->prd_search($query);
$this->load->view('prd_search', ['prd_search' => $prd_search]);
}
And this code is MODEL
function prd_search($query)
{
$q = $this->db->from('purchase')
->like('item_name', $query)
->get();
return $q->num_rows();
}
CI's input->post() is an array containing POST data. The second parameter of CI's active record like() expects a string. If you mean to pass an individual field value, you will need to access that index:
<input name="search_value">
$query = $this->input->post('search_value'); //notate the field being used here
Then you can query where like:
$this->db->like('column', $query); //query is now a string
Alternatively, if you mean to pass the entire array, you can use where_in()
$this->db->where_in('column', $query); //if you assign $query to $this->input->post();

PHP MySQL fatal error after moved to real server

I have tested my application in localhost and works very well, after I moved to server, the scripts related to MySQL query are die,
class Test {
public function check_duplicate_username($username, $mysqli)
{
$sql = $mysqli->prepare("SELECT username FROM `account` WHERE username=?");
$sql->bind_param('s', $username); // line 44
$sql->execute();
$res = $sql->get_result();
if($res->num_rows !== 0){
return false;
}
return true;
}
public function get_main_cate($mysqli)
{
$sql = $mysqli->query("SELECT name FROM `category` ORDER BY `id` DESC");
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
}
To fetch the result:
$test = new Test;
if(!$test->check_duplicate_username($email, $mysqli)){
$data['error']['email'] = 'email has been used';
}
echo '<select>';
$cat = $test->get_main_cate($mysqli);
while($obj = $cat->fetch_object()){ //line 134
echo '<option>'.$obj->name.'</option>';
}
echo '</select>';
From the error log:
PHP Fatal error: Call to a member function bind_param() on boolean in /path/to/html/root/classes/test.php on line 44
[24-Mar-2016 02:36:26 America/Chicago] PHP Fatal error: Call to a member function fetch_object() on boolean in /path/to/html/root/sign-up.php on line 134
what's wrong with this issue? Is that cause by missing of library in the server? PHP in hosting is Version 5.6.18, whereas in localhost is Version 5.6.19.
The issue seems to be that your database is empty. The error is clear:
Call to a member function fetch_object() on boolean
You tried to call the function fetch_object on a variable of type boolean. The variable on the line is called $cat and is the result of the function $cat = $test->get_main_cate($mysqli);.
Inside that function you are loading all categories and return them. If no categories are found you return false. You have to add a check if $cat is false before trying to iterate over the results, something like
$cat = $test->get_main_cate($mysqli);
if ($cat != false) {
while($obj = $cat->fetch_object()){ //line 134
echo '<option>'.$obj->name.'</option>';
}
}
Instead of checking your that your data exists with !, try using empty(). If I understand the usage correctly, this method should check for all (or most) types of invalid or empty data requests.
According to http://php.net/manual/en/function.empty.php
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
Try changing this line:
if(!$test->check_duplicate_username($email, $mysqli))
to
if(empty($test->check_duplicate_username($email, $mysqli)))
If this doesn't work. You may just need to consider a 2-step check to verify data exists. Keep in mind I have not tested this method with your code.
Warning from source:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
Try to use this query
$sql = $mysqli->prepare('SELECT username FROM account WHERE username=?');
$sql->bind_param('s', $username); // line 44

Create limit posting for users

I want to make users only can create maximum 10 post per day.
Here is my controller:
$id_user=$this->session->userdata('id');
$sql ="SELECT COUNT(id_post) as max_post FROM post
WHERE post.id_user=$id_user
AND DATE(post.time)=DATE(NOW())";
$result = $this->db->query($sql);
if ($result > 10) //line number 17
{
//redirect to home
} elseif($result <= 10 ) //line number 20
{
//then do post
Then is getting error like this:
A PHP Error was encountered
Severity: Notice
Message: Object of class CI_DB_mysql_result could not be converted to int
Line Number: 17
A PHP Error was encountered
Severity: Notice
Message: Object of class CI_DB_mysql_result could not be converted to int
Line Number: 20
Any answer?
Many thanks...
if ($result > 10)
$result Is the resource itself, you have to fetch data from it. $result itself is not what you are looking for. Fetch the required field from result.
For example
$row = $result->row();
if ($row->max_post > 10)
if(mysql_num_rows($result)>10)
{
}
try using this

Catchable fatal error: Argument 1 passed to ... must be an instance of ..., boolean given, called in ... on line ... and defined in ... on line

I have added a CMS to my server. I am just wondering why I keep getting this error on a Page to purchase a subscription.
This is the error;
Catchable fatal error: Argument 1 passed to ObjectArray::fromMySQLiResult() must be an instance of
mysqli_result, boolean given, called in
C:\inetpub\wwwroot\model\FactoryObjects\User.php on line 71
and defined in C:\inetpub\wwwroot\lib\ObjectArray.php on line 284
Line 71 has the following;
public function getOrders() {
$objectArray = new ObjectArray();
$result = $this->getConnection()->query("SELECT * FROM vip_orders WHERE user_id =
'" . $this->id. "'");
$objectArray->fromMySQLiResult($result); (<Line 71<)
return $objectArray;
}
Line 284 has the following;
public function fromMySQLiResult(mysqli_result $result) (<Line 284<)
{
$this->clear();
while ($row = $result->fetch_object())
{
$this->add($row);
}
return $this;
}
Please let me know if any other information is necessary for you to help me fix this error!
Thanks!
(Note: For those assisting, could you please explain what exactly is the problem? For example, what the function is and why it is not working, thank you.)
Your definition of fromMySQLiResult(mysqli_result $result) states that the function requires a parameter of type mysqli_result. However, you are passing the result of mysqli::query() which might also be of type boolean in case of failure.
To prevent the error, make sure $result is actually a query result similar to the example in the documentation:
if ($result) {
$objectArray->fromMySQLiResult($result);
} else {
// handle error
}

Codeigniter error Message: Missing argument 1 for mtree::insert_to_righ

i got this error message while running my Php codeigniter project :
A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for mtree::insert_to_right(), called in
C:\AppServ\www\News\application\controllers\bcontroller.php on line 20
and defined
Filename: models/mtree.php
Line Number: 28
this is my model function :
function insert_to_right($row, $direct_id) {
$left_parent = $this->get_right_parent($direct_id);
$row->members_direct_id = $left_parent;
$this->db->insert('table1', $row);
$sql = "INSERT INTO table2 (child, parent)
VALUES (" . $this->db->escape($row->members_id) . ", " . $this->db->escape($left_parent) . ")";
$this->db->query($sql);
}
function get_right_parent($id) {
return $id;
}
Since the function insert_to_right($row, $direct_id) requires two arguments, either you can pass in those two variables when you call them, or you can assign default values for it like insert_to_right($row = '....', $direct_id = '...'). I don't think you can just pass in any default variable as this would insert it into the database, so I would recommend you pass in the argument from the controller.

Categories