Perl <TMPL_LOOP> issue - arrays

I am working on a Perl script, but I am having an issue I can't really overcome. Here is my code:
my #rowses = ();
while ( #list = $sth->fetchrow_array())
{
%row = ();
if($list[30] == 1)
%row = (
cod_cliente => $list[1],
rag_soc => $list[2],
p_iva => $list[11],
IDanagrafica => $list[0],
tabella => $tab,
IDanagraficaE => $list[0],
tabellaE => $tab,
checkbox => "checked",
);
$LOL = \%row;
print $cgi->p($LOL);
}
else
{
%row = (
cod_cliente => $list[1],
rag_soc => $list[2],
p_iva => $list[11],
IDanagrafica => $list[0],
tabella => $tab,
IDanagraficaE => $list[0],
tabellaE => $tab,
checkbox => "",
);
$LOL = \%row;
print $cgi->p($LOL);
}
push (#rowses, \%row);
}
$template->param(table => \#rowses);
$template->param(tab => $tab);
When I try to print, for debugging, the reference to a row ($LOL), it prints nothing, and when I print the reference at #rowses, it is an array full of all the same hash, the last one the fetched by from the statement.
The weird is, if I print a hash row per time, without referencing it, it prints them well, and all of them.
I am doing that for passing the array reference, containing all the hashes, to a TMPL_LOOP, and print them; but it print a long list of only the last row fetched.
Thanks in advance to everyone who will help me.

Your %row is the same variable for each iteration of the while loop. You store just the reference to it in #rowses, which means if you change %row, all the references point to the changed hash. You should define a new %row for each iteration of the loop, e.g. by using
my %row;
indead of
%row = ();
Why $LOL is not printed: If the first argument to p is a hash reference, it is interpreted as the attributes of the <p>.

Related

update multiple array values with multiple ids in laravel 5.1

My query as follows
$dueid = array('1','2');
for($n = 0; $n< count($post['percentage']); $n++) {
$due=invoiceduedates::whereIn('id',$dueid)
->update(array(
'percentage' => $post['percentage'][$n],
'amount'=>$post['pamount'][$n],
'date' => $post['date'][$n]
)
);
}
But in table,at 1st and 2nd ids the 2nd array data is getting updated.Please help me to sort it out.
I don't know what you what to get... but in this way it's normal that you get what you get. I can only sugest you to try like this:
$dueid = array('1','2');
$dues = invoiceduedates::whereIn('id',$dueid)->get();
for($n = 0; $n< count($post['percentage']); $n++) {
$due = $dues->find($dueid[$n+1]);
$due->update(array(
'percentage' => $post['percentage'][$n],
'amount'=>$post['pamount'][$n],
'date' => $post['date'][$n]
)
);
}

Strange behaviour of Perl's push function

I am writing a dedicated ICS (iCalendar file) parser.
I pass an array to a subroutine. All variables are single values apart from $notdates which is a comma-separated list of dates.
#entryl = ($dtstart, $dtend, $attendee, $lastmod, $uid, $notdates);
&entrytoarray(#entryl);
sub entrytoarray {
# print Dumper #_;
my $shiftdur = (&stamptoepoc($_[1]) - &stamptoepoc($_[0])) / 60 / 60;
my $attendee = $_[2];
my $deleted = $_[5];
$attendee =~ /ATTENDEE;USER-KEY=([^;]*);CN=([^;]*);.*:(.*)/;
my %ehash = (
"STARTDATE" , &stamptodate($_[0]),
"ENDDATE" , &stamptodate($_[1]),
"STARTSTAMP" , $_[0],
"ENDSTAMP" , $_[1],
"USERKEY" , $1,
"CN" , $2,
"EMAIL" , $3,
"LASTMOD" , $_[3],
"UID" , $_[4],
"DURATION" , $shiftdur
);
# Only keep current data
my $fdays = 4;
my $tdays = 7;
chomp(my $curstamp = `TZ="UTC" date -d "$fdays days" +"%Y%m%d%H%M00"`);
chomp(my $stpstamp = `TZ="UTC" date -d "$tdays days" +"%Y%m%d%H%M00"`);
if (($_[0] > $curstamp) && ($_[1] < $stpstamp)) {
if (defined($deleted)) {
my #deleted = split /,/, $deleted;
foreach (#deleted) {
if ($_ ne $_[0]) {
push(#entry, \%ehash);
}
}
}
else {
push(#entry, \%ehash);
}
}
print Dumper #entry;
This works mostly as expected:
$VAR1 = {
'DURATION' => '5',
'STARTSTAMP' => '20141122230000',
'UID' => '20141114T010539Z--1092363482',
'LASTMOD' => '20141118214419',
'STARTDATE' => '2014-11-22 23:00:00',
'EMAIL' => 'xxxxxxxxxxxxx',
'ENDDATE' => '2014-11-23 04:00:00',
'CN' => 'xxxxxxxxxxx',
'ENDSTAMP' => '20141123040000',
'KEY' => 'xxxxxxxxxxxxxxxxxx'
};
$VAR2 = {
'EMAIL' => 'xxxxxxxxxxxxx',
'ENDDATE' => '2014-11-23 23:00:00',
'ENDSTAMP' => '20141123230000',
'KEY' => 'xxxxxxxxxxx',
'CN' => 'xxxxxxxxxxxxxx',
'STARTDATE' => '2014-11-23 19:00:00',
'LASTMOD' => '20141118205901',
'UID' => '20141114T010456Z--1092363482',
'DURATION' => '4',
'STARTSTAMP' => '20141123190000'
};
$VAR3 = $VAR2;
Where is the $VAR3 = $VAR2 coming from?
My guess is that this section is the culprit:
foreach (#deleted) {
if ($_ ne $_[0]) {
push(#entry, \%ehash);
}
}
If you have several values in the array, the if-statement can be true twice, and thus push a value twice. Unless this is wanted behaviour, I would make sure that only one value is pushed. You can do this by using grep instead:
if (grep { $_ ne $_[0] } #deleted) {
push #entry, \%ehash;
}
Note that this replaces the foreach loop.
Your array #entry contains hash references. Data::Dumper is saying that the first and second elements of the array refer to two different hashes, while the third refers to the same hash as the second.
You don't show where #entry comes from, but I would expect all three elements to be references to %ehash.
The problem is that, if you keep pushing a reference to %ehash onto #entry, they all point to the same data item, and the intermediate states of the hash won't be recorded.
Unless you mean entrytoarray to push only one copy of %ehash (in which case there's a separate problem that we can't see) you need to fix it by either writing
push #entry, { %ehash }
which copies the hash and returns a reference to the copy, or you can declare and populate %ehash inside the foreach loop, which will create a new hash each time around the loop.

Using array for MySQL Select Statement

Apologies in advance if i use the wrong definition of a word...I am using SimpleCart to pass $.Post variables to a PHP page. If i print the array i get
Array ( [currency] => CAD [shipping] => 0 [tax] => 1.69 [taxRate] => 0.13 [itemCount] => 3 [item_name_1] => Dinner Plate [item_quantity_1] => 1 [item_price_1] => 5 [item_options_1] => code: 110 [item_name_2] => Side Plate [item_quantity_2] => 1 [item_price_2] => 4 [item_options_2] => code: 125 [item_name_3] => Mixing Bowl [item_quantity_3] => 1 [item_price_3] => 4 [item_options_3] => code: 66 )
What I am struggling with (and going around in circles) is a method to do the following..
Explode the [item_options] variable to strip out the CODE: part of the value and just leave the numeric section.
concatenate these values into a string so i can use a SELECT statement to only pull records that have an ID passed in the [item.options].
I understand how to explode a single parameter, but cannot work out how to loop through the array, explode the key and create the value i need for the SQL.
Any help or pointers to relevant tutorials would be much appreciated
$codes = array();
foreach ($_POST as $key => $value) { // Loop through the $_POST array
if (preg_match('/^item_options_/', $key)) { // And validate the value
$item_arr = explode(' ', $value);
$item_id = $item_arr[1]; // Get the ID number from the value
if (is_numeric($item_id)) { // Validate it
$codes[] = $item_id; // Add it to the array we're building
}
}
}
$codes_string = implode(', ', $codes); // Concatenate them into a string that can be used in a SQL IN clause
$sql = "SELECT * from table WHERE id IN ($codes_string)"; // Build the SQL

codeigniter update table row with new data array where

I have a database record with a uniqueID/PrimaryKe (OrderNumber)
I want to update the record with new data for that same PrimaryKey, OrderNumber.
My Controller is:
$data = array(
'CustomerName' => $this->input->post('customer'),
'CustomerAccountCode' => $this->input->post('accountcode'),
'PeriodStart' => substr($this->input->post('period'), 0,10),
'OrderUnitOfMeasure' => $this->input->post('buom'),
'CreditLimit' => $this->input->post('creditlimit'),
'BalanceBeforeOrder' => $this->input->post('currentbalance'),
'BalanceAfterOrder' => $this->input->post('newbalance'),
'OrderLines' => $this->input->post('orderlines'),
'TotalCost' => $this->input->post('grandtotal'),
'AverageDiscount' => $this->input->post('avediscount'),
'TotalCubes' => $this->input->post('grandtotalcubes'),
'TreatedCubes' => $this->input->post('grandtotaltreatedcubes'),
'SpecialComments' => $this->input->post('specialcomments'),
'CustomerReference' => $this->input->post('customerref'),
'ordernumber' => $this->input->post('ordernumber')
);
$this->sales_model->update_order_data($data);
My model is:
function update_order_data($q){
$this->db->where('CustomerOrderID', 'OrderNumber'); //ordernumber being post input ordernumber in array
$query = $this->db->update('Customer_Order_Summary');
}
So what I want is :
update 'Customer_Order_Summary'
set 'CustomerName'="$this->input->post('customer')",
set 'CustomerAccountCode'="$this->input->post('accountcode')",
//rest of set statements for each column and corresponding post
where 'CustomerOrderID'='OrderNumberInArray'//(post value)
This update statement is not working, any pointers would be appreciated.
Thanks as always,
Remove 'ordernumber' from your $data array and pass it separately
$this->sales_model->update_order_data($this->input->post('ordernumber'),$data);‌
The query should be like
function update_order_data($key,$q){
$this->db->where('CustomerOrderID', $key);
$query = $this->db->update('Customer_Order_Summary',$q);
}
Try:
function update_order_data($q)
{
$this->db->where('CustomerOrderID', $q['OrderNumber']);
$this->db->update('Customer_Order_Summary',$q);
return $this->db->affected_rows();
}
Note: Usually, in update functions, I have 2 arguments eg:
function update_something($pk,$data)
{
$this->db->where('primary_key', $pk);
$this->db->update('database_table',$data);
return $this->db->affected_rows();
}

Add an array to a session array

I have an array from a MySQL query of ID numbers that I'm trying to add to a Session Array that is already created. For some reason, my code is adding an array inside the Session Array already in place rather than just adding the ID numbers to the Session. What is causing this to happen?
Here is my PHP...
//Find members of this group and create an array to add to cart
$deletedgroupmembersquery = "SELECT * FROM groupmember WHERE group_id='$groupid'";
$deletedgroupmembers = mysql_query($deletedgroupmembersquery) or die('SQL Error :: '.mysql_error());
if (mysql_num_rows($deletedgroupmembers) > 0) {
$groupmembers = mysql_num_rows($deletedgroupmembers);
$cart = array();
while(($deletedmembersrow = mysql_fetch_assoc($deletedgroupmembers))) {
$cart[] = $deletedmembersrow['contact_id'];
}
//Add the array to the cart session
if (isset($cart)) {
$_SESSION['cart'] = array();
array_push($_SESSION[cart],$cart);
} else {
}
Here is the session the above code is creating..
Array ( [cart] => Array ( [0] => Array ( [0] => 1362 [1] => 1371 [2] => 2241 ) )
Thanks for any help.
$cart is already an array. When you do:
array_push($_SESSION[cart],$cart);
you're pushing it as a sub-array of $_SESSION['cart']. I think you just want:
$_SESSION['cart'] = $cart;
You're defining $cart as an array before you push it into $_SESSION[cart]...so you're pushing an array into an array. Try something like this:
if (!empty($cart)) {
$_SESSION['cart'] = array();
foreach ($cart AS $item) {
array_push($_SESSION['cart'], $item);
}
}
You can also just place the array_push inside your while(), and stick the $_SESSION['cart'] = array() before the while(), and it will achieve the same thing.

Resources