unset all elements of an array and resue it in php - php

i used unset method to empty my array it does but when i initilize same array again to reuse it in my code it gives the fatal error
Unsupported operand types
although other unset are working fine but only one array with integer type values have problem.
Any kind of help would be appreciated
here is my piece of code:
<?php
for ($citycount = 0; $citycount < $count; $citycount ++) {
$loc_qry = "SELECT `ID` as LocationID, `name` as LocationName FROM `territories` where `formatID` = 43 and `territorylevelID` = 77 and `parentID` = '" . $cityID_arr[$citycount] . "'";
$loc_qry_res = mysql_query($loc_qry) or die($loc_qry . "<br><br>" . mysql_error());
while ($rs_loc = mysql_fetch_array($loc_qry_res)) {
$location_id_arr[] = $rs_loc['LocationID'];
$location_name_arr [] = $rs_loc['LocationName'];
}
$count_loc = count($location_id_arr);
for ($i = 0; $i < $count_loc; $i++) {
$location_scores = "SELECT ((SUM(sa.achievedScore) / SUM(sa.totalScore)) * 100) as Score
FROM `scoreanalysis` as sa
WHERE `formatID` = 43 and `waveID` = '" . $wave_id_arr[0] . "' and `territoryID` = '" . $location_id_arr[$i] . "'";
$location_scores_res = mysql_query($location_scores);
while ($res_location_score = mysql_fetch_array($location_scores_res)) {
$location_scores_arr[] = intval($res_location_score['Score']);
}
if ($location_scores_arr[$i] != NULL) {
$divider = $divider + 1;
}
$cityscore = $cityscore + $location_scores_arr[$i];
//echo $location_id_arr[$i];
//echo $location_name_arr[$i]."<br>";
}
$total = $cityscore / $divider;
$city_qry = "SELECT `ID` as cityID, `name` as cityName FROM `territories` where `ID` = '" . $cityID_arr[$citycount] . "'";
$city_qry_rs = mysql_query($city_qry) or die($city_qry . "<br><br>" . mysql_error());
while ($city_name = mysql_fetch_array($city_qry_rs)) {
$cityname = $city_name['cityName'];
}
echo $cityname;
echo intval($total) . "%";
$total = 0;
$cityscore = 0;
unset($location_id_arr);
unset($location_name_arr);
$location_id_arr[] = array();
$location_name_arr[] = array();
unset($location_scores_arr);
$location_scores_arr[] = array();
$city_scores_arr [] = intval($total);
}
?>

The [] syntax is for adding an element to the end of an array; it's not valid for a variable you have just unset. Instead of trying to clear the array at the end of each iteration of the loop, you should be creating a new array at the beginning of each iteration, i.e.:
for ($citycount = 0; $citycount< $count; $citycount ++)
{
$location_id_arr = array();
$location_name_arr = array();
$location_scores_arr = array();
$loc_qry = "SELECT `ID` as LocationID, `name` as LocationName FROM `territories` where `formatID` = 43 and `territorylevelID` = 77 and `parentID` = '".$cityID_arr[$citycount]."'";
$loc_qry_res = mysql_query($loc_qry) or die($loc_qry."<br><br>".mysql_error());
...
}

Related

PHP Oracle inserting data on loop got incorrect id

I'm continuing my previous question.
Now I need to insert the value to DB. But ID inserted is not correct as on my database master.
$qModel = oci_parse($c1, "SELECT MODELID, MODEL_NAME FROM WA_LFO_TBL_MODEL
WHERE ACTIVE = 'Y'");
oci_execute($qModel);
while($dModel = oci_fetch_array($qModel))
{
$qDtl2 = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_MODEL_CONFIGURATION WHERE MODELID_FK = '" . $dModel['MODELID'] . "'");
oci_execute($qDtl2);
while($dDtl2 = oci_fetch_array($qDtl2))
{
$q = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_REJECT_PROCESS WHERE MODELID_FK = '" . $dModel['MODELID'] . "' ORDER BY SORT_NO ASC");
oci_execute($q);
while($d = oci_fetch_array($q))
{
$idkeys[] = $d['RP_ID'];
$keys[] = $d['RP_NAME'];
}
$values = array_fill(0, count($keys), 0);
$values = array_combine($keys, $values);
for($i = $readRowAfter; $i < count($linesReject); $i++)
{
// if the fileReject is "Tue, Sep 18<tab>2018<tab>23:59:53<tab>"
$dateobjReject = DateTime::createFromFormat($createFromFormat, $linesReject[$i]);
// check if date is in your Timespan
if($dateobjReject < $toDateTime && $dateobjReject > $fromDateTime)
{
$rowsintimespanReject++; // count if in timespan
$lineContent = explode("\t", $linesReject[$i]);
// loop through line elements and count them
$x = 0;
for ($j = 0; $j < count($keys); $j++) {
if (!isset($lineContent[$j])) {
continue;
}
// remember position of last not empty column
if (trim($lineContent[$j]) != '') {
$x = $j;
}
}
if ($x > 0) {
$values[$keys[$x]]++;
}
}
}
$i = 0;
$sql = "";
foreach ($values as $value)
{
if($value != 0)
{
$sql = oci_parse($c1,"INSERT INTO WA_LFO_TBL_REJECT_OUTPUT(MODELID_FK, QUANTITY, RPID_FK, CONFIGURATIONID_FK)VALUES('" . $dModel['MODELID'] . "', '" . $value . "', '" . $idkeys[$i] . "', '" . $dDtl2['CONFIGURATIONID'] . "')");
oci_execute($sql);
}
$i++;
}
}
}
As you can see that I'm trying to insert the date on foreach function.
But inserted data for ID is not correct for RPID_FK.
I realize maybe something wrong with the code, tried to get the solution but still stuck on it.
Is something wrong on that code?

PrestaShop: Create new cart rule using custom code

I created a code to create new cart rule, it works great, but there's one issue, the restriction by product is not working...
Hoping someone can help, I tried looking the PrestaShop classes and controllers, and I tried to replicate, but this is what I got to and didn't work.
$coupon = new Discount();
$coupon->quantity = 1;
$coupon->quantity_per_user = 1;
$coupon->id_discount_type = 2;// reduction amount
$coupon->value = '10';
$coupon->id_customer = 1;
$coupon->minimum_amount = 0;
$coupon->minimum_amount_currency = 1;
$coupon->minimum_amount_tax = 0;
$coupon->minimum_amount_shipping = 0;
$coupon->quantity = 1;
$coupon->quantity_per_user = 1;
$coupon->product_restriction = 1;
$coupon->product_rule_group[] = 1;
$coupon->product_rule_group_1_quantity = 1;
$coupon->product_rule_1[] = 1;
$coupon->product_rule_1_1_type = 'products';
$coupon->product_rule_select_1_1[] = 9;
$coupon->reduction_percent = 100;
$coupon->reduction_amount = 0;
$coupon->reduction_currency = 1;
$coupon->reduction_tax = 0;
$coupon->apply_discount_to = 'specific';
$coupon->reductionProductFilter = '191072 Air Freshener Refill';
$coupon->reduction_product = 6;
$coupon->free_gift = 0;
$start_date = date('Y-m-d H:i:s');
$coupon->date_from = $start_date;
$end_date = date('Y-m-d H:i:s'); //some end date
$coupon->date_to = $end_date;
$gen_pass = strtoupper(Tools::passwdGen(8));
$vouchercode = 'somecode';
$name_v = $vouchercode.'-'.$gen_pass;
$namelang = array();
$namelang[1] = $name_v;
$namelang[2] = $name_v;;
//Add Name array
$coupon->name = $namelang;
$current_language = 1;
$coupon->id_customer = 1;
// fixed bug for currency
$coupon->reduction_currency = 1;
$coupon->minimum_amount_currency = 1;
$code_v = $vouchercode.'-'.$gen_pass;
$coupon->code = $code_v;
//$coupon->minimal = $coupon->value;
$coupon->active = 1;
//$coupon->cart_display = 1;
//$coupon->cart_rule_restriction = 0;
$coupon->description = '';
$coupon->highlight = 1;
$coupon->add();
We recommend you to use following code to create a cart rule.
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_shop
set id_cart_rule = ' . (int) $cart_rule_id . ', id_shop = ' . (int) $this->context->shop->id);
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_lang
set id_cart_rule = ' . (int) $cart_rule_id . ', id_lang = ' . (int) $this->context->language->id . ',
name = "' . strip_tags($coupon_name) . '"');
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule_group
set id_product_rule_group = NULL, id_cart_rule = ' . (int) $cart_rule_id . ',
quantity = 1');
$product_rule_group_id = Db::getInstance()->Insert_ID();
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule
set id_product_rule = NULL, id_product_rule_group = ' . (int) $product_rule_group_id . ',
type = "products"');
$product_rule_id = Db::getInstance()->Insert_ID();
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule_value
set id_product_rule =' . (int) $product_rule_id . ', id_item = ' . (int) $id_product . '');
i know it doesn't matter now but, anyways, if you're looking for a way to tie or add products to a specific cart rule, this might help
$products = [1 => "32232", 2 => "23232", 3 => "45343"];
So, after you $cartrule->add() you get, $cartRuleId = $cartrule->id
$coupon->product_restriction = 1; //enable product restriction
$coupon->reduction_product = -2; // write this only if you want the discount to be applied on the products in the cart and not the whole cart
(new Cart( $cart->id) )->addCartRule( (int) $cartRuleId); // apply the cart rule to this existing cart
# first, save `id_cart_rule` & `quantity` and get id_product_rule_group
Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule_group` (`id_cart_rule`, `quantity`)
VALUES ('.(int)$cartRuleId.', "'.(int)$qty.'")');
$id_product_rule_group = Db::getInstance()->Insert_ID();
# second, save `id_product_rule_group` & `type` and get id_product_rule
Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule` (`id_product_rule_group`, `type`)
VALUES ('.(int)$id_product_rule_group.', "'.$type.'")');
$id_product_rule = Db::getInstance()->Insert_ID();
# finally, using id_product_rule assign products
foreach ($products as $id) {
$values[] = '('.(int)$id_product_rule.','.(int)$id.')';
}
$values = array_unique($values);
if (count($values)) {
Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule_value` (`id_product_rule`, `id_item`) VALUES '.implode(',', $values));
}
If you don't want to engage in complex codes, this method may help you:
create Sample disabled coupon with your restrictions on admin panel
create object of your Sample coupon on your php file
clone object to newObject
change (code and active and etc) then add new coupon from it

Returning JSON from a PHP function

I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));

Why does the loop execute only once?

I have the following small code which manipulate tweets data. I expect my loop to iterate 10 times. However, what happens is that it iterates only once and then exits, with no sign of any error relating to MySQL or otherwise.
$query = "select data from tweets where `screen_name` = 'username' limit 10";
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
$tweets = mysqli_fetch_assoc($tweetsq);
$tweets_count = mysqli_num_rows($tweetsq);
echo $tweets_count . '<br />'; //See output
$count = 0;
foreach ($tweets as $raw_tweet) {
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
$is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0;
$is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0;
$entity_holder = array();
$has_hashtag = $has_url = $has_mention = $has_media = 0;
foreach ($tweet->entities as $type => $entity) {
if (is_array($entity) && count($entity) < 1) {
//continue;
} else {
$entity = array_pop($entity);
switch ($type) {
case 'hashtags' : $has_hashtag = 1; break;
case 'urls' : $has_url = 1; break;
case 'user_mentions' : $has_mention = 1; break;
case 'media' : $has_media = 1; break;
default :
}
}
}
echo 'Updating recorde... <br />';
$query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'";
$result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
var_dump($result); //See output
$count++;
echo '<br />';
}
echo $count;
Output:
10 //This is the value of $tweets_count
Updating recorde...
bool(true) //The result of the UPDATE query
1 //The value of $count at the end of script. It SHOULD be 10
mysqli_fetch_assoc fetches a single row as an associative array where the key is the column name and the value is the column value. The correct way to use it would be to iterate over the result set until the fetch returns NULL, indicating that there are no more rows to fetch:
while ($row = mysqli_fetch_assoc($tweetsq)) {
$raw_tweet = $row["data"];
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
# etc...

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

Categories