Count result array to string conversion error in codeigniter - arrays

I am using this method in my model to get a count result from my database:
function members($group_id)
{
$this->db->where('group_id',$group_id);
$query = $this->db->query('SELECT COUNT(group_id) FROM member');
return $query;
}
And in my controller there is this method:
function total_members ()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
echo $members;
}
And am getting this weird error which says:
Severity: 4096
Message: Object of class CI_DB_mysqli_result could not be converted to string
Filename: controllers/Payment.php

You need to return a result set which requires another call. In this case I suggest row(). Try these revised functions.
function members($group_id)
{
$this->db->where('group_id', $group_id);
$query = $this->db->query('SELECT COUNT(group_id) as count FROM member');
return $query->row();
}
function total_members()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
if(isset($members))
{
echo $members->count;
}
}
Learn about the different kinds of result sets here

Try this
Model
function members($group_id) {
return $this->db->get_where('member', array('group_id' => $group_id))->num_rows();
}
Controller
function total_members() {
$group_id = $this->input->post('group_id');
$this->load->model('member_model');
$members = $this->member_model->members($group_id);
print_r($members);
}
In codeigniter there is num_rows() to count the rows. For more information check the documentation .

Related

Multiple collections in an array (session variable) — Property does not exist

I'am trying to fetch a session variable if the user is a guest. The variable is called "cart" and is set like this:
$product = new Collection((object) [
'product_id' => $request->pId,
'amount' => $request->amount,
'variations' => $variations
]);
Session::push('cart', $product);
Then I later fetch it:
if(Auth::check()){
$cartProducts = ShoppingCartItem::where('user_id', '=', Auth::user()->id)->get();
}else{
$cartProducts = Session::get('cart');
}
foreach($cartProducts as $product){
dd($product);
$totalAmount += $product->amount;
$totalPrice += (PriceHelper::getProductPrice($product->product->id, $product->amount));
}
The problem here is that dd($product) still outputs an array (the session variable array I assume) which means that for example $product->amount does not exist.
This is the output from dd($product):
You can either access the values using get():
foreach ($cartProducts as $product) {
$totalAmount += $product->get('amount');
$totalPrice += PriceHelper::getProductPrice($product->get('product_id'), $product->get('amount'));
}
or as an array:
foreach ($cartProducts as $product) {
$totalAmount += $product['amount'];
$totalPrice += PriceHelper::getProductPrice($product['product_id'], $product['amount']);
}
or you could use sum() on the collection instead of using foreach:
$cartProducts = collect(Session::get('cart'));
$totalAmount = $cartProducts->sum('amount');
$totalPrice = $cartProducts->sum(function ($product) {
return PriceHelper::getProductPrice($product['product_id'], $product['amount']);
});
Edit
For a quick fix if you need $product to be an object you could do something like:
$cartProducts = collect(Session::get('cart'))->map(function ($item) {
return (object)$item->toArray();
});
Hope this helps!

database query return an array composed of stdClass

im having trouble here getting value from a record.
Here's what i want to do:
1. Getting a record from db
2. Convert the query result to array
3. Display the array[0], but got error undefined offset:1
The var_dump() : array(1) { [0]=> object(stdClass)#23 (1) { ["nama"]=> string(9) "Test Name" } }
Tried the query by myself, and it return a record :
|username|nama |
|Testuser|Testnama|
so how can i get the 'Testuser'?
model/verify_login_model
function getinfo($username) {
$this->db->select('nama', 'username');
$this->db->from('tb_userInfo');
$this->db->where('username', $username);
$this->db->limit(1);
$result = $this->db->get();
if($result->num_rows()==1) {
return $result->result();
} else {
return false;
}
}
controller/verify_login
public function index(){
$this->load->model('verify_login_model');
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->verify_login_model->verify($username, $password);
if($result == $username) {
$row = $this->verify_login_model->getinfo($username);
echo var_dump($row);
$sessiondata = array('name'=>$row[0], 'username'=>$row[1]);
$this->session->set_userdata($sessiondata);
$name = $sessiondata['name'];
$this->load->view('home_view', $name);
} else {
redirect('login');
}
}
view/home_view
<html>
<head></head>
<body>
welcome, <?php echo $name?>
</body>
</html>
your model returns an array of objects, as you use
return $result->result();
in order to get the result as a plain array use:
return $result->result_array();
read more about generating query results here
According to CI query result displays
https://ellislab.com/codeigniter/user-guide/database/results.html
->result() This function returns the query result as an array of objects,
What about the stdClass - check out here https://stackoverflow.com/a/931419/2513428
To get your result you have to do as following
$sessiondata = array('name'=>$row[0]->nama, 'username'=>$row[0]->yourfield);
To visualise this a bit it's like array(1) { [0]=> object(stdClass)#23 (1) { Your query result } } and to get the data you point the object $var[0]->Object. But you can also change to the result_array() and treat it as an array not an object as it is now.
For result_array()
$sessiondata = array('name'=>$row[0]['nama'], 'username'=>$row[0]['yourfield']);
Hope this will help you.

row() return null for specific field

Im trying to save specific field from a record into a session, for my user-role. The problem here is i cannot take any other field except nama.
controller/verify_login
public function index(){
$this->load->model('verify_login_model');
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->verify_login_model->verify($username, $password);
if($result == $username) {
$name = $this->verify_login_model->getinfo($username);
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata('username', $username);
$this->session->set_userdata('name', $name);
$this->load->view('home_view');
} else {
redirect('login');
}
model/verify_login_model
function verify($username, $password){
$this->db->select('username', 'password');
$this->db->from('tb_user');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
return $username;
} else {
return false;
}
}
function getinfo($username) {
$this->db->select('nama', 'username');
$this->db->from('tb_userInfo');
$this->db->where('username', $username);
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
$result = $query->row();
return $result->nama;
} else {
return false;
}
}
view
<?php echo $this->session->userdata['name']?>
the var_dump($result) : object(stdClass)#22 (1) { ["nama"]=> string(4) "test" }
if i change the return $result->nama; to $result->username; i get error : Undefined property: stdClass::$username even tho im sure 200% there's username field in the table, and tried the query directly.
There's an error in your select statement, it must be
$this->db->select('nama,username');
You are separating each column, and that's not correct, all of the columns go in one string, that's why it tells you its undefined since the only column you are sending is nama and you're sending username as the second parameter for the select.
Here's a link on active record for CodeIgniter 2.2.0

CakePHP 3.x: log as serialized array

I'm writing my own parser log for CakePHP.
I only need one thing: that is not written a log "message" (as a string), but a serialized array with various log information (date, type, line, stack traces, etc.).
But I don't understand what method/class I should rewrite, although I have consulted the APIs. Can you help me?
EDIT:
For now I do the opposite: I read the logs (already written) and I transform them into an array with a regex.
My code:
$logs = array_map(function($log) {
preg_match('/^'.
'([\d\-]+\s[\d:]+)\s(Error: Fatal Error|Error|Notice: Notice|Warning: Warning)(\s\(\d+\))?:\s([^\n]+)\n'.
'(Exception Attributes:\s((.(?!Request|Referer|Stack|Trace))+)\n)?'.
'(Request URL:\s([^\n]+)\n)?'.
'(Referer URL:\s([^\n]+)\n)?'.
'(Stack Trace:\n(.+))?'.
'(Trace:\n(.+))?(.+)?'.
'/si', $log, $matches);
switch($matches[2]) {
case 'Error: Fatal Error':
$type = 'fatal';
break;
case 'Error':
$type = 'error';
break;
case 'Notice: Notice':
$type = 'notice';
break;
case 'Warning: Warning':
$type = 'warning';
break;
default:
$type = 'unknown';
break;
}
return (object) af([
'datetime' => \Cake\I18n\FrozenTime::parse($matches[1]),
'type' => $type,
'error' => $matches[4],
'attributes' => empty($matches[6]) ? NULL : $matches[6],
'url' => empty($matches[9]) ? NULL : $matches[9],
'referer' => empty($matches[11]) ? NULL : $matches[11],
'stack_trace' => empty($matches[13]) ? (empty($matches[16]) ? NULL : $matches[16]) : $matches[13],
'trace' => empty($matches[15]) ? NULL : $matches[15]
]);
}, af(preg_split('/[\r\n]{2,}/', $logs)));
For now I do the opposite: I read the logs (already written) and with a regex I transform them into an array.
The problem is this is terribly expensive. and that it would be better to do the opposite: to write directly to the logs as a serialized array.
I think what you want to do is write your own LogAdapter.
You simply create a class ArrayLog (extends BaseLog) as mentioned in the docs and configure cakePHP to use it. Within the log function you append the information like $level, $message and $context to a file as an array. This will result in a log file with several arrays that then can be split.
That being said, I would suggest to log to the database and read it out instead of parsing.
Ok, that's it!
(note that this code is absolutely experimental, I have yet to test it properly)
One interesting thing that I want to do: for each log, write to the serialized file and also simultaneously in a plan file.
This allows me either to read logs as a plain text file, or they can be manipulated using the serialized file.
use Cake\Log\Engine\FileLog;
class SerializedLog extends FileLog {
protected function _getLogAsArray($level, $message) {
$serialized['level'] = $level;
$serialized['datetime'] = date('Y-m-d H:i:s');
//Sets exception type and message
if(preg_match('/^(\[([^\]]+)\]\s)?(.+)/', $message, $matches)) {
if(!empty($matches[2]))
$serialized['exception'] = $matches[2];
$serialized['message'] = $matches[3];
}
//Sets the exception attributes
if(preg_match('/Exception Attributes:\s((.(?!Request URL|Referer URL|Stack Trace|Trace))+)/is', $message, $matches)) {
$serialized['attributes'] = $matches[1];
}
//Sets the request URL
if(preg_match('/^Request URL:\s(.+)$/mi', $message, $matches)) {
$serialized['request'] = $matches[1];
}
//Sets the referer URL
if(preg_match('/^Referer URL:\s(.+)$/mi', $message, $matches)) {
$serialized['referer'] = $matches[1];
}
//Sets the trace
if(preg_match('/(Stack )?Trace:\n(.+)$/is', $message, $matches)) {
$serialized['trace'] = $matches[2];
}
$serialized['full'] = date('Y-m-d H:i:s').' '.ucfirst($level).': '.$message;
return (object) $serialized;
}
public function log($level, $message, array $context = []) {
$message = $this->_format(trim($message), $context);
$filename = $this->_getFilename($level);
if (!empty($this->_size)) {
$this->_rotateFile($filename);
}
$pathname = $this->_path . $filename;
$mask = $this->_config['mask'];
//Gets the content of the existing logs and unserializes
$logs = #unserialize(#file_get_contents($pathname));
if(empty($logs) || !is_array($logs))
$logs = [];
//Adds the current log
$logs[] = $this->_getLogAsArray($level, $message);
//Serializes logs
$output = serialize($logs);
if (empty($mask)) {
return file_put_contents($pathname, $output);
}
$exists = file_exists($pathname);
$result = file_put_contents($pathname, $output);
static $selfError = false;
if (!$selfError && !$exists && !chmod($pathname, (int)$mask)) {
$selfError = true;
trigger_error(vsprintf(
'Could not apply permission mask "%s" on log file "%s"',
[$mask, $pathname]
), E_USER_WARNING);
$selfError = false;
}
return $result;
}
}

codeigniter multiple table joins

function in codeigniter model is not working. I'm getting http error 500 because of below code in codeigniter model function. if I remove this code.. code is working fine.
function get_ad_by_user($a,$b)
{
$this->db->select('title,ci_categories.category,ci_subcategories.subcategory,state,city,locality,ad_website,description,phone_number,address,image_token1,image_token2');
$this->db->from('ci_pre_classifieds');
$this->db->join('ci_categories', 'ci_categories.category_id = ci_pre_classifieds.category');
$this->db->join('ci_subcategories', 'ci_subcategories.subcategory_id = ci_pre_classifieds.sub_category');
$this->db->where('ci_pre_classifieds.id',$a);
$this->db->where('ci_pre_classifieds.ad_string_token',$b);
$q=$this->db->get();
$this->db->last_query();
log_message('debug','******query'.$this->db->last_query().'********');
if($q->num_rows()==1)
{
foreach($q->result_array() as $row)
{
$data['title]=$row['title'];
$data['category']=$row['ci_categories.category'];
$data['sub_category']=$row['ci_subcategories.subcategory'];
$data['state']=$row['state'];
$data['locality']=$row['locality'];
$data['ad_website']=$row['ad_website'];
$data['description']=$row['description'];
$data['phone_number']=$row['phone_number'];
$data['address']=$row['address'];
}
}
else
{
$data['message']="sorry either classified expired or deleted";
}
return $data;
}
I'm getting error in for each block..if I remove everything working...How to copy $row array in $data array
$data['title]=$row['title']; has a ' missing.
This could be the reason but without that error message, it's hard to tell.
Also, you may want to reduce the function to the following:
function get_ad_by_user($a,$b)
{
$data = array();
$this->db->select('title,ci_categories.category,ci_subcategories.subcategory,state,city,locality,ad_website,description,phone_number,address,image_token1,image_token2');
$this->db->from('ci_pre_classifieds');
$this->db->join('ci_categories', 'ci_categories.category_id = ci_pre_classifieds.category');
$this->db->join('ci_subcategories', 'ci_subcategories.subcategory_id = ci_pre_classifieds.sub_category');
$this->db->where('ci_pre_classifieds.id',$a);
$this->db->where('ci_pre_classifieds.ad_string_token',$b);
$q=$this->db->get();
log_message('debug','******query'.$this->db->last_query().'********');
if($q->num_rows()==1)
{
$data[] = $q->row_array();
}
else
{
$data['message']="sorry either classified expired or deleted";
}
return $data;
}
If you are only returning one row in your query, you can simply use $q->row_array() or $q->row() to return the single row.
Just in case, I would also declare $data = array() at the start of your get_ad_by_user function, otherwise it "could" complain that $data does not exist.

Resources