cant update data through array in codeigniter - php

i am not able to update data through array in Codeigniter (PHP),
I want to update or set column premium_id and premium to 0 when column premium_count reduce to 0
Controller Function :-
$premium_count = !empty($logged_user[0]->premium_count) ? $logged_user[0]->premium_count : '0';
if($premium_count == '0') {
$data = array(
'premium_count' => '0',
'premium_id' => '0',
'premium' => '0'
);
} else {
$data = array(
'premium_count' => $premium_count-1
);
}
$this->admin_model->updateData('users', $data, $this->session->userdata('userid'));
Model Function (sql Query) :-
public function updateData($table,$data,$id)
{
$this->db->where('id',$id);
$this->db->update($table,$data);
}
It works when premium_count has value like 1,2,3.. but when it reduce to 0, It wont update or set above column to 0.

Please try and remove the quotes from 0s.
I mean change
if($premium_count == '0') {
$data = array(
'premium_count' => '0',
'premium_id' => '0',
'premium' => '0'
);
to
if($premium_count == 0) {
$data = array(
'premium_count' => 0,
'premium_id' => 0,
'premium' => 0
);
Hope it helps.

replace this part to place zero as integer instead of string
$premium_count = !empty($logged_user[0]->premium_count) ? $logged_user[0]->premium_count : 0; // <- remove '' over zero
and check like this
if($premium_count == 0) { // <- remove '' over zero
$data = array(
'premium_count' => '0',
'premium_id' => '0',
'premium' => '0'
);
} else {
$data = array(
'premium_count' => $premium_count-1
);
}

Related

Bigcommerce Pagination in php

i hope all are doing well, I am working on Bigcommerce API integration with PHP, as API fetches 50 records per page, but what i want is it starts fetching all records 50 and then from next page store it in an array and then that data should be dropped to the database, i am confused with how to pass current page id to the api
self::set_config($channel);
$page = 1;
$url=self::$current_channel->api_url."v3/catalog/products?page=$page";
$headers = self::getHeader($channel);
$body = '';
$response=self::make_api_request($url,$body,"GET",$headers);
// echo "<pre>";
// print_r($response->meta->pagination->total);
// echo "</pre>";
// exit;
if(isset($response->data)) {
foreach ($response->data as $item) {
$record = self::get_product_detail($channel,$item->id); // get detail from api
$record = isset($record->data[0]) ? $record->data[0] : NULL;
if ($record)
{
$mappedItems = [
'parent_sku_id' => null,
'sku' => $record->id,
'channel_sku' => $record->sku,
'variation_id' => $record->option_set_id,
'name' => $record->name,
'ean' => $record->upc, //$data->mpn, $data->gtin
'price' => $record->price,
'stock_qty' => isset($record->inventory_level) ? $record->inventory_level : null,
'channel_id' => self::$current_channel->id,
'is_live' => isset($record->is_visible) ? $record->is_visible : "1",
'type1' => 'main_product',
];
$parent_sku_id = self::save_channel_products((object)$mappedItems); // will return product id from products table
$headers = self::getHeader($channel);
$url=self::$current_channel->api_url."v3/catalog/products/$item->id/variants";
$server_output = self::make_api_request($url,$body,"GET",$headers);
if ($parent_sku_id && isset($record->option_set_id)) {
foreach ($server_output->data as $variation) {
$mappedItems = [
'parent_sku_id' => $parent_sku_id,
'sku' => $variation->sku_id,
//'sku' => $variation->product_id,
'channel_sku' => $variation->sku,
// 'variation_id' => $variation->sku_id,
'variation_id' => $variation->id,
'name' => $record->name,
'ean' => $variation->upc, //$variation->mpn, $variation->gtin
'price' => $variation->calculated_price,
'stock_qty' => isset($variation->inventory_level) ? $variation->inventory_level : null,
'channel_id' => self::$current_channel->id,
'is_live' => isset($record->is_visible) ? $record->is_visible : "1",
'type1' => 'variation',
];
//echo '<pre>';print_r($new_item);die;
// self::save_channel_products((object)$mappedItems);
if(isset($response->meta->pagination->total))
{
self:: $products_fetched = self:: $products_fetched + 50; // for offset
if($response->meta->pagination->total > self:: $products_fetched)
{
$lim=($response->meta->pagination->total - self:: $products_fetched);
$lim= $lim > 50 ? 50:$lim;
//self:: channelProducts(null,self:: $products_fetched ,$lim);
}
echo $page = $response->meta->pagination->current_page;
}
}
}
}
}
I am looking forward for help with php? i am little confused how to set per page request in api, every time it fetches same records in api i want to make it as per pagination changes
you can send a key from url with get method ex: p=1
and replace this code : $page = 1; with :
$page = isset($_GET['p']) ? $_GET['p'] : 1;

Pagination count wrong Cakephp 1.2

I had auction bid list (debit for each auction was equal 1). I changed View code for "Debit" for showing "Auction Id" count. (you can see pic.).
But now I have problem with pagination. It has to show 26 but you can see 93.
I want to show result like in picture but with correct pagination.
Here is my code
In Controller:
$this->paginate = array(
'conditions' => array('Bid.user_id' => $user_id),
'limit' => 100,
'order' => array('Bid.created' => 'desc'),
'contain' => array('Auction' => array('Product'))
);
$this->set('bids', $this->paginate());
In Model: override paginateCount()
function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$sql = "
SELECT user_id,
auction_id,
description,
debit,
COUNT( * ) AS my_auct,
`credit`,
`created`
FROM `bids`
WHERE `user_id` = {$this->User->id}
GROUP BY auction_id, credit
";
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
}
How can fix this issue only in controller (not using paginateCount) and put this query result into View (now I made calculating in View).
Thanks in advance!
I solved my problem. Here my code in controller
$this->paginate = array('conditions' => array('Bid.user_id' => $user_id),'fields' => array('COUNT(auction_id) as my_auct', 'Bid.*'), 'group' => array('Bid.auction_id', 'Bid.credit'), 'limit' => 10000, 'order' => array('Bid.created' => 'desc'), 'contain' => array('Auction' => array('Product')));
I found paginateCount function here and added in model:
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$conditions = compact('conditions');
if ($recursive != $this->recursive) {
$conditions['recursive'] = $recursive;
}
unset( $extra['contain'] );
$count = $this->find('count', array_merge($conditions, $extra));
if (isset($extra['group'])) {
$count = $this->getAffectedRows();
}
return $count;
}
Only thing I can't show in "Credit" column are all values (when I grouped by auction_id and credit, it shows to me only one 15 and 100). I want to show all values in credit column
Any ideas?

Comparing two associated arrays and updating one based on the comparison

So I have a couple of associated arrays of equal length and associations, and need to compare them. If the voted key in the first array has a value, I need to update the voted key value in the second array with that same value.
// create the arrays...
$votes_array = [];
array_push($votes_array, array(
'id' => '1',
'voted' => '-1'
)
);
array_push($votes_array, array(
'id' => '1',
'voted' => ''
)
);
$menu_array = [];
array_push($menu_array, array(
'id' => '1',
'voted' => ''
)
);
array_push($menu_array, array(
'id' => '1',
'voted' => ''
)
);
I tried this but but couldn't even get the result to echo true.
foreach ($votes_array as $votes_array_key => $votes_array_value) {
foreach ($menu_array as $menu_array_key => $menu_array_value) {
if( $votes_array_key == 'voted' && ($votes_array_value == '1' || $votes_array_value == '-1') ){
echo 'true';
// Update the $menu_array array index with the associated 'voted' value.
}
}
}
So it would end up with $menu_array[0]['voted'] being '-1'.
How do I achieve this?
Thanks.
Edit:
I've also modified the accepted answer to cater for when the length of votes_array varies.
foreach($votes_array as $votes_key => $votes_vote) {
if( ! $votes_vote['voted'] )
{
continue;
}
else
{
$getVoteId = $votes_array[$votes_key]['id'];
foreach($menu_array as $menu_key => $menu_vote)
{
if($menu_array[$menu_key]['id'] == $getVoteId)
$menu_array[$menu_key]['voted'] = $votes_vote['voted'];
}
}
}
Assuming those are strings and arrays are equal in length like you said this would be simple one from top of the head:
foreach($votes_array as $key => $vote) {
if( ! $vote['voted']) continue;
$menu_array[$key]['voted'] = $vote['voted'];
}
It seems you set your voted keys, so im using empty instead of isset to check for a non-value.
foreach($votes_array as $key=>$vote) {
if (!empty($vote["voted"])) {
$menu_array[$key]["voted"] = $vote["voted"];
}
}

How can I fix this query to return only items with a certain value in its subarray?

I'm trying to modify a voting script(Thumbsup) I need this query to only return only array items that have their 'cat' => '1' in the subarray (proper term?)
<?php $items = ThumbsUp::items()->get() ?>
Here's an example of the live generated array from my database
array (
0 =>
array (
'id' => 1,
'name' => 'a',
'cat' => '1',
),
1 =>
array (
'id' => 2,
'name' => 'b',
'cat' => '2',
),
2 =>
array (
'id' => 3,
'name' => 'c',
'cat' => '2',
),
)
Is this possible by just modifying the query?
edit: heres function get()
public function get()
{
// Start building the query
$sql = 'SELECT id, name, url, cat, closed, date, votes_up, votes_down, ';
$sql .= 'votes_up - votes_down AS votes_balance, ';
$sql .= 'votes_up + votes_down AS votes_total, ';
$sql .= 'votes_up / (votes_up + votes_down) * 100 AS votes_pct_up, ';
$sql .= 'votes_down / (votes_up + votes_down) * 100 AS votes_pct_down ';
$sql .= 'FROM '.ThumbsUp::config('database_table_prefix').'items ';
// Select only either open or closed items
if ($this->closed !== NULL)
{
$where[] = 'closed = '.(int) $this->closed;
}
// Select only either open or closed items
if ($this->name !== NULL)
{
// Note: substr() is used to chop off the wrapping quotes
$where[] = 'name LIKE "%'.substr(ThumbsUp::db()->quote($this->name), 1, -1).'%"';
}
// Append all query conditions if any
if ( ! empty($where))
{
$sql .= ' WHERE '.implode(' AND ', $where);
}
// We need to order the results
if ($this->orderby)
{
$sql .= ' ORDER BY '.$this->orderby;
}
else
{
// Default order
$sql .= ' ORDER BY name ';
}
// A limit has been set
if ($this->limit)
{
$sql .= ' LIMIT '.(int) $this->limit;
}
// Wrap this in an try/catch block just in case something goes wrong
try
{
// Execute the query
$sth = ThumbsUp::db()->prepare($sql);
$sth->execute(array($this->name));
}
catch (PDOException $e)
{
// Rethrow the exception in debug mode
if (ThumbsUp::config('debug'))
throw $e;
// Otherwise, fail silently and just return an empty item array
return array();
}
// Initialize the items array that will be returned
$items = array();
// Fetch all results
while ($row = $sth->fetch(PDO::FETCH_OBJ))
{
// Return an item_id => item_name array
$items[] = array(
'id' => (int) $row->id,
'name' => $row->name,
'url' => $row->url,
'cat' => $row->cat,
'closed' => (bool) $row->closed,
'date' => (int) $row->date,
'votes_up' => (int) $row->votes_up,
'votes_down' => (int) $row->votes_down,
'votes_pct_up' => (float) $row->votes_pct_up,
'votes_pct_down' => (float) $row->votes_pct_down,
'votes_balance' => (int) $row->votes_balance,
'votes_total' => (int) $row->votes_total,
);
}
return $items;
}
thanks.
You can easily modify "get()" to add the desired functionality:
public function get($cat = null)
{
$where = array();
if ($cat !== null) {
$where[] = 'cat = '. (int) $cat;
}
// ... original code ...
}
Usage:
$items = ThumbsUp::items()->get(1);

PHP Variables for if statements

Ok, I am wanting to do something like this:
$which = !empty($param_id) ? "['groups'][$param_id]" : "['groups']";
And than I'd like it to be able to do something like so...
$all_groups . $which = array(
-1 => array(
'id' => '-1',
'name' => $txt['parent_guests_only'],
'checked' => in_array('-1', $checked) || in_array('-3', $checked),
'is_post_group' => false,
)
And I need it to build an array like so, if !empty($param_id)
$all_groups['groups'][$param_id] = array(the array info);
But if $param_id is empty it should do the this instead:
$all_groups['groups'] = array(the array info);
I don't think I can concatenate it or can I?
Can someone please help me here? This is happening many many times throughout a function, so I don't want to use if... else... statements every single time. Would be too many, thinking of a 1 fast approach for all of them.
Thanks :)
EDIT, here is the function in question:
function ListGroups($checked = array(), $unallowed = array(), $order = array(), $param_id = 0)
{
global $context, $smcFunc, $txt;
// We'll need this for loading up the names of each group.
if (!loadLanguage('ManageBoards'))
loadLanguage('ManageBoards');
if (empty($checked))
return array();
$all_groups['groups'][$param_id] = array();
if (!in_array('-1', $unallowed))
// Guests
$all_groups['groups'][$param_id] = array(
-1 => array(
'id' => '-1',
'name' => $txt['parent_guests_only'],
'checked' => in_array('-1', $checked) || in_array('-3', $checked),
'is_post_group' => false,
)
);
if (!in_array('0', $unallowed))
{
// Regular Members
if (!empty($all_groups['groups']))
$all_groups['groups'][$param_id] += array(
0 => array(
'id' => '0',
'name' => $txt['parent_members_only'],
'checked' => in_array('0', $checked) || in_array('-3', $checked),
'is_post_group' => false,
)
);
else
$all_groups['groups'][$param_id] = array(
0 => array(
'id' => '0',
'name' => $txt['parent_members_only'],
'checked' => in_array('0', $checked) || in_array('-3', $checked),
'is_post_group' => false,
)
);
}
// Load membergroups.
$request = $smcFunc['db_query']('', '
SELECT group_name, id_group, min_posts
FROM {db_prefix}membergroups
WHERE id_group > {int:is_zero}',
array(
'is_zero' => 0,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
{
if (!in_array($row['id_group'], $unallowed))
{
$all_groups['groups'][(int) $param_id][(int) $row['id_group']] = array(
'id' => $row['id_group'],
'name' => trim($row['group_name']),
'checked' => in_array($row['id_group'], $checked) || in_array('-3', $checked),
'is_post_group' => $row['min_posts'] != -1,
);
}
}
$smcFunc['db_free_result']($request);
// Let's sort these arrays accordingly!
if (!empty($order))
{
$all_groups['groups'][$param_id] = sortGroups($all_groups['groups'][$param_id], $order);
$context['group_order' . $param_id] = implode(', ', $order);
}
else
{
$context['group_order' . $param_id] = '';
sort($all_groups['groups'][$param_id]);
$x = 0;
foreach ($all_groups['groups'][$param_id] as $key => $value)
{
$x++;
$context['group_order' . $param_id] .= $x < count($all_groups['groups'][$param_id]) ? $value['id'] . ', ' : $value['id'];
}
}
return $all_groups['groups'][$param_id];
}
I need to do a check for !empty($param_id), if so, it needs to build the $all_groups['groups'] array without the $param_id.
So will need to add in a check for if (!empty($params_id)) build the array like so: $all_groups['groups'][$params_id] else build it like this instead: $all_groups['groups']. I don't want a bunch of if... else... statements in here, just a 1 or 5 liner would be GREAT!
Thanks Guys :)
Don't overcomplicate it. :)
$array = array(
/* contents */
);
if (!empty($param_id)) {
$all_groups['groups'][$param_id] = $array;
} else {
$all_groups['groups'] = $array;
}
I don't know what $all_groups['groups'] looks like before this; if it was empty, I'd shorten this to:
$all_groups['groups'] = array(
/* contents */
);
if (!empty($param_id)) {
$all_groups['groups'] = array($param_id => $all_groups['groups']);
}
if (!empty($param_id)) {
$which = &$all_groups['groups'][$param_id]
} else {
$which = &$all_groups['groups'];
}
$which = array(
-1 => array(
'id' => '-1',
'name' => $txt['parent_guests_only'],
'checked' => in_array('-1', $checked) || in_array('-3', $checked),
'is_post_group' => false,
);
unset($which); // unset $which, if you want to use this variable
// in this scope once again
Generally speaking, references are the solution. See #zerkms' answer.
However, if at all possible, I would try to redesign your data structures such that you don't have to resort to this type of conditional behavior. For example, using default as the default missing key:
$which = !empty($param_id) ? $param_id : 'default';
$all_groups['groups'][$which] = array( ... );
I don't know if it's possible in your case, but this could be easier to manage.
Other potential solutions:
$tmp = array( ... );
if ($cond)
$foo = $tmp;
else
$bar = $tmp;
or:
function make_array( ... )
{
return array( ... );
}
if ($cond)
$foo = make_array( ... );
else
$bar = make_array( ... );

Categories