update checkbox value in CodeIgniter - php

I have an update query problem in CodeIgniter. I am trying to solve that problem but I can't. I have one array $arrpartnerId=([0=>1,[1]=>4,[3]=>5 like..) and my other array is $promotionData['promotion_id']. The inserting into checkbox value is correct, but the updating checkbox value is not working.
My model function is:
public function update_promotion($promotionData, $partnerData) {
// print_r( $promotionData['promotion_id']);
$arrPartnerId = $partnerData['partner_id'];
print_r($partnerData['partner_id']);
if (is_array($arrPartnerId) > 0) {
foreach ($arrPartnerId as $partnerId) {
$this->db->set('promotion_id', $promotionData['promotion_id']);
$this->db->where('partner_id', $partnerId);
$this->db->update('partner_promotion_relation');
}
}
}

If your array is like this,
$arrPartnerId = array(
0 => 1,
1 => 4,
2 => 5
);
And
$promotionData['promotion_id'] = 123; //assumption
Then try this,
if(sizeof($arrPartnerId) > 0 )
{
foreach( $arrPartnerId as $partnerId)
{
$this->db->set('partner_id', $partnerId );
$this->db->where('promotion_id', $promotionData['promotion_id'] );
$this->db->update('partner_promotion_relation');
}
}
It will resolve the problem.

Related

Why is there not enough memory in the simplest loop and with an array of 3 elements?

There is a function that displays categories ranging from the very top:
function getFullCategoryName($strCategoryId, $arrCategories)
{
$strCategoryIdPaent = NULL;
$arrCategoryCurr = isset($arrCategories[$strCategoryId]) ? $arrCategories[$strCategoryId] : NULL;
$arrCategoriesNames = [];
while (is_array($arrCategoryCurr)) {
$arrCategoriesNames[] = $arrCategoryCurr['title'];
if ($arrCategoryCurr['parentId'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
$arrCategoryCurr = $arrCategories[$arrCategoryCurr['parentId']];
} else {
$arrCategoryCurr = NULL;
}
}
krsort($arrCategoriesNames);
return implode(' > ', $arrCategoriesNames);
}
With just 3 array elements, I get an error:
"Allowed memory size of 134217728 bytes exhausted"
I understand that I am using something wrong. Please, help me understand what exactly.
This is my input array:
$arrCategories = array (
193450 =>
array (
'id' => '193450',
'parentId' => '193450',
'title' => 'Blood glucose meter',
),
193451 =>
array (
'id' => '193451',
'parentId' => '193450',
'title' => 'Sugar test strips',
),
193452 =>
array (
'id' => '193452',
'parentId' => '193452',
'title' => 'Blood glucose meter',
),
);
This is the call to the function:
$strCategoryId = 193450;
getFullCategoryName($strCategoryId, $arrCategories);
The while (is_array($arrCategoryCurr)) loop never ends as the else block of $arrCategoryCurr = NULL; is never called.
This happens because you have a loop where a node id is the same as his parent id. Look at your array:
....
'id' => '193450',
'parentId' => '193450',
...
To fix it modify the if statement to:
if ($arrCategoryCurr['parentId'] && $arrCategoryCurr['parentId'] != $arrCategoryCurr['id'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
Your (sample) data has an issue based on my reading of your function.
The parentId and index are the same in some items. This would create an infinite loop based on what I can work out from the question.
A better structure would be something like the following, with some error checking in the loop:
function getFullCategoryName($strCategoryId, $arrCategories) {
// set a base / default value
$arrCategoriesNames = [];
// do we even have anything to work with?
if (isset($arrCategories[$strCategoryId])) {
// at least one entry
do {
// get the title
$arrCategoriesNames[] = $arrCategories[$strCategoryId]['title'];
// get the next id and error check the data
if ((isset($arrCategories[$strCategoryId]['parentId'])) &&
($strCategoryId != $arrCategories[$strCategoryId]['parentId'])) {
// next index found and not the same
$strCategoryId = $arrCategories[$strCategoryId]['parentId'];
} else {
// either no parentId or a parentId that matches the current
// index. If that is the case, go no further.
$strCategoryId = false;
}
// you could add another error check if you like.
// if (count($arrCategoriesNames) == count($arrCategories)) {
// // go no further as data has a loop
// $strCategoryId = false;
// }
} while($strCategoryId);
// sort the data? why?
krsort($arrCategoriesNames);
}
// return a string
return implode(' > ', $arrCategoriesNames);
}
And testing you sample array;
$result = getFullCategoryName(193450,$arrCategories);
var_dump($result);
Returns the following:
string(19) "Blood glucose meter"

how to insert array of data to database (for example add more products to cart ) using api

Hi all am trying to insert array of data to database using api in laravel .my task is i need to insert data from postman using some paramters(inputs)
when i run url the data is not inserting into database .
getting output status::true. am not getting any errors .how to solve this to insert data?
below is my code:
public function addToCart(){
$input = Input::all();
$data['status'] = 0;
$data['error'] = true;
// print_r($input);
$carty=array($input['cart']);
if(isset($input['user_id']) && isset($carty)> 0 ){
foreach($carty as $key => $val){
if(!empty($val['quantity']) && !empty($val['price']) && !empty($val['sku']) && !empty($val['qrcode']) && !empty($val['product_id']))
{
echo "here";
$totalPrice = $val['quantity']* $val['price'];
$cartId = [];
$cartId[] = DB::table('jocom_cart')->insertGetId(array(
'user_id' => $input['user_id'],
'product_id' => $val['product_id'],
'sku' => $val['sku'],
'quantity' => $val['quantity'],
'price' => $val['price'],
'total_price' => $totalPrice,
'qrcode' => $val['qrcode']
));
}
}
}
else{
$data['message'] = 'All field are required.';
}
return Response::json($data);
}
I saw some syntax errors in your posted code
$input = Input::all()
Must be (; missing)
$input = Input::all();
and
DB::table('jocom_cart')>insertGetId
must be (with ->, not >)
DB::table('jocom_cart')->insertGetId
Hope it's could resolved the problem

Initialize a Multidimensional Array

i am trying to render values from mysql query and insert them into a multidimensional array. I am able to create the array and insert all the values from the query into the array.
the problem occurs when a value does not exist in the database and i try to echo out the array setting. I get the followig error:
Undefined offset: 2
might be easier if i show you want i mean
my class contains lots of functions that echo dynamically set values
i.e
public $answer=array();
public function questionOne()
{
return $this->answers[$row['period_id']]['question_one'];
}
the above values are set from the dynmic rendering of values from the query below:
while ($row = mysqli_fetch_array ($results, MYSQLI_ASSOC))
{
$this->answers[$row['period_id']][] = $row['question_one'];
$this->answers[$row['period_id']][] = $row['question_two'];
}
This fuction works as long as the values exist in the database. So, i need a way to initlize the array.
i tried doing this ;
$this->answers = $this->theResponseArray();
public function theResponseArray()
{
return $array = array (
1 => array (
0 => null,
1 => null,
),
2 => array (
0 => null,
1 => null,
),
3 => array (
0 => "",
1 => "",
),
3 => array (
0 => "",
1 => "",
)
);
}
but all that happened is that it rendered the entire array as null and prevented from placing new values into the array.
UPDATE
i have placed the entire code on fiddle:
the code
You can check if value in array exists (by isset), and then do something with it, for example:
public function questionOne()
{
if (isset($this->answers[$row['period_id']]['question_one']) {
return $this->answers[$row['period_id']]['question_one'];
} else {
return 'no question'; //or '', or whatever
}
}
Edit:
The only thing that is different bout your getQuestionWeekXyz function is the number of week, so you should put it in one place. Then you can use foreach to go through questions in your week table:
public function getQuestionByWeek($weekNo) {
$result = '';
//if there are no questions for this week
if (!isset($this->answers[$weekNo]) || !is_array(this->answers[$weekNo])) {
return $result;
}
$result .= "<form action='index.php?view=$this->postDestination' method='post' >";
foreach ($this->answers[$weekNo] as $questionNumber => $questionText) {
$questionNumber++;
$result .= "<p>
Question Week {$this->numberToString($weekNo)}: <textarea name='cycleWeekQuestion{$this->numberToString($questionNumber)}' cols='$this->col' rows='$this->row' style='font-family: Tahoma; font-size: 12pt' />{$questionText}</textarea>
</P>";
}
$result .= "<input type='hidden' name='cycleWeekId' value='{$weekNo}'>
<span class='hideSubmit'><input type='submit' name='submit' size='20' style='font-family: Tahoma; width: 200px; height: 25pt; font-size: 14pt' value='Submit'></span>
</form>";
return $result;
}
public function numberToString($number)
{
switch($number) {
case 1: return 'One';
case 2: return 'Two';
case 3: return 'Three';
case 4: return 'Four';
}
return $number;
}
public function questionsWeekOne()
{
return $this->getQuestionByWeek(1);
}
public function QuestionsWeekTwo()
{
return $this->getQuestionByWeek(2);
}
public function QuestionsWeekThree()
{
return $this->getQuestionByWeek(3);
}
public function QuestionsWeekFour()
{
return $this->getQuestionByWeek(4);
}

Find out if the price was zero when looking through php array of price history/changes

I have all the price changes in a array like this (date, pricechange). It is always in date order:
$pricehistory = array (
'2013-11-04' => 10,
'2013-11-10' => 0,
'2013-12-01' => 10
);
What I need is to find out if the price for a specific date was zero.
function was_free($date) {
// return boolean
}
was_free('2013-11-11'); //should return true;
was_free('2013-12-01'); //should return false;
Can someone please help me figuring out how to do this? I think I need to loop through the $pricehistory array backwards, but I'm not sure how to do it.
//$default - returned if price is not exits
function was_free($price_history, $current_date, $default = FALSE) {
if(isset($price_history[$current_date]))
{
return empty($price_history[$current_date]);
}
$current_timestamp = strtotime($current_date);
$history_timestamp = array();
foreach ($price_history as $date => $price)
{
$history_timestamp[strtotime($date)] = $price;
}
$history_timestamp[$current_timestamp] = NULL;
ksort($history_timestamp);
$previous_price = ($default) ? FALSE : TRUE;
foreach ($history_timestamp as $timestamp => $price)
{
if($timestamp == $current_timestamp)
{
break;
}
$previous_price = $price;
}
return empty($previous_price);
}
$price_history = array (
'2013-11-04' => 10,
'2013-11-10' => 0,
'2013-12-01' => 10
);
// run !!
var_dump(was_free($price_history, '2013-11-03'));
var_dump(was_free($price_history, '2013-11-04'));
var_dump(was_free($price_history, '2013-11-09'));
var_dump(was_free($price_history, '2013-11-10'));
var_dump(was_free($price_history, '2013-11-11'));
var_dump(was_free($price_history, '2013-12-01'));
var_dump(was_free($price_history, '2013-12-02'));
Try:
function was_free($date) {
return array_key_exists($date,$pricehistory) && $pricehistory[$date] === 0;
}
Since the $pricehistory isn't in the scope of the function, you may pass it as a parameter or access it using global.

Unset Not Clearing Array Key/Value

I have form submission that redirects based on the results of a survey. On the landing page, I call a function to process query string, query the database and return results as an array for in-page processing.
function surveyResults() {
if($goodtogo) {
$survey = $wpdb->get_results(...,ARRAY_A);
$name_has_space = strpos(trim($q_name_field[0]),' ');
if($name_has_space === false) {
$q_first_name = $q_name_field[0];
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
} else {
$q_first_name = substr(trim($q_name_field[0]),0,$name_has_space);
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
}
$survey['name']['q_fname'] = $q_first_name;
$results = $survey;
} else {
$results = false;
}
return $results;
}
Output:
Array (
[0]=> Array (
'key' => 'value'
)
...
[n]=> Array (
'key' => 'value'
)
['name'] => Array (
[q_fname] => MyName
)
)
Which is perfect – except – each time I test the page, the $survey[0-n] results change as queried, but the $survey['name']['q_fname'] still holds the previous value MyName.
I have tried adding unset($survey['name']['q_fname']); immediately after setting $results = $survey; but that doesn't seem to make a difference. Do I need to unset($results) or use a reference &$fname...
What am I missing here?
Thanks
I'm macgregor, and I'm an idiot. Missed a critical piece of condition in the query.

Categories