createQueryBuilder warning Undefined variable: list - arrays

When I Run createQueryBuilder Query by passing Array as a parameter value showing as array undefined.
$list = array('13','197');
$queryBuilder = function($repo) use ($user) {
return $repo->createQueryBuilder('p')
->where('p.id IN (:stores)')
->setParameter('stores',$list);
->orderBy('p.name', 'ASC');
}

You need to include your $list variable in lambda-function scope. To do that you need to provide this variable in use-part of lambda-function definition:
$list = array('13','197');
$queryBuilder = function($repo) use ($user, $list) {
return $repo->createQueryBuilder('p')
->where('p.id IN (:stores)')
->setParameter('stores',$list);
->orderBy('p.name', 'ASC');
}

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!

Count result array to string conversion error in codeigniter

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 .

NOT an array reference error in Perl

I'm getting an error in Perl and I can't work out why.
Error: Not an ARRAY reference at Service.pm, line 20
my $array = [ { name => 'George', surname => 'Marley' } ];
my $helper = CustMessage->new();
$helper = CustMessage->getMessage($array);
then in my utility file I have:
sub getMessage {
my ($self, $args) = #_;
my $stringsArray = shift;
my $strings = Service->new({
serviceId => $self->_serviceId(),
});
return unless $strings;
$strings->getStrings($stringsArray);
}
and then in the Service method is:
sub getStrings {
my ($stringsArray, $self) = shift;
my #keys = map({ $_->{'name'} } #{$stringsArray});
my $key = join('', #keys);
$key = MIME::Base64::encode($key);
my %results;
$results{$key} = $self->_callStrings->($stringsArray);
$results{$key}->initialize();
$results{$key} = $self->{serviceCalls}->{getStrings};
return $self->{serviceCalls}->{getStrings};
}
The error is on line 2 of the getStrings method in Service.pm:
my #keys = map({ $_->{'name'} } #{$stringsArray});
The lines
my $helper = CustMessage->new();
$helper = CustMessage->getMessage($array);
are very odd. You are creating a new CustMessage object in $helper and immediately discarding it and overwriting it with the result of
CustMessage->getMessage($array);
which, apart from any inheritance that may be going on, is identical to
getMessage('CustMessage', $array);
and I am suspecting that you don't have a real class defined as you call it your "utility file"
Because getMessage receives its arguments like this
my ($self, $args) = #_;
my $stringsArray = shift;
you are left with
($self, $args) = ('CustMessage', $array)
$stringsArray = 'CustMessage'
and you never use $args again so your array reference is lost.
I cannot be sure what it is you actually want, because, as I said, I suspect that you don't have a proper CustMessage.pm file. But you could try
my $helper = CustMessage->new;
my $message = $helper->getMessage($array);
and then
sub getMessage {
my ($self, $stringsArray) = #_;
...
}
RE: I'm getting an error in Perl and I can't work out why. Error: Not an ARRAY reference at Service.pm, line 20
Try
my ($self, $stringsArray) = #_;
instead of
my ($stringsArray, $self) = shift;
# $self is always undef here due one element list assignment
since getStrings() is object method and object instance is always first element in #_ array.

Wordpress use array key and value to set data attribute

I have setup an array of product values. I need to set each array key to the data-attribute and the value to the data-attribute value
<li data-name="product1" data-price="49.99" data-rating="4.5"></li>
So in Wordpress I have this filter hook
function product_data_sorting( $product_attrs, $product, $terms) {
global $post;
// Product Attributes
$product_attrs['name'] = $post->post_name;
$product_attrs['price'] = $product->price;
$product_attrs['rating'] = $product->get_average_rating();
$product_attrs['newness'] = $post->post_modified;
// Product Categories
foreach ($terms as $term) {
$categories[] = $term->slug;
}
$product_attrs['categories'] = $categories;
foreach ($product_attrs as $attribute) {
if ( is_array($attribute) ) {
//This is a category
}
else {
$results[] = 'data-' . $key . '="' . '$attribute' . '"';
}
}
return $results
}
add_filter( 'add_sorting', 'product_data_sorting', 10, 3 );
I am getting all the correct data pushed in to the $product_attrs array that I need, but not sure how to work with the array key and values so that in the $results array it would be formatted like this:
$results = (data-name="product1", data-price="49.99", data-rating="4.5");
Hope that makes some sense
thanks
You would need key=>value pair within foreach.
$ignored = array ('newness'); // array to maintain what attributes you want to ignore
foreach ($product_attrs as $key => $attribute) {
if ( is_array($attribute) ) {
//This is a category
}
else {
if(!inarray($key, $ignored)
$results[] = 'data-' . $key . '="' . $attribute . '"';
}
}
Also note that $attribute isn't enlcosed in single quotes as you have in the question. Variables inside single quote can not be parsed

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