Foreach loop involving $date Variable CAKEPHP - cakephp

I'm new to cakephp and I'm trying to write a for each loop that will get each event that is less than or equal to (<=) today's date.
First of all I'm not really sure if a for each loop is the best way to go about this, I have also been considering a while loop or an if statement but I don't know how else to get each entry from the database.
So here's where I've got to so far.
DATABASE HEADINGS
<?php foreach ($events['Event']['startDate'] <= $date): ?>
DATABASE RESULTS
Unfortunately I receive the following error:Parse error: syntax error, unexpected ')' in /homepages/3/d439567456/htdocs/cakephp/app/View/Events/live.ctp on line 22 (which is the for each loop line.
Any help would be great thanks and examples would be appreciated!

you cannot just change how PHP works.
Usually, events also have a numeric index for more than one "Event".
foreach ($events as $event) {
if ($event['Event']['startDate'] <= $date) {} else {}
}
To access a specific startDate directly, e.g. the first, you would need 0 as key:
if ($events[0]['Event']['startDate'] <= $date) {} else {}
But you cannot abuse foreach this way, though.

Related

Using and filling an ArrayList with .Add() questions using Powershell

I'm attempting to add performance to a script that has an array of data of over 10,000 entries, then use it in a foreach-object statement to fill a blank ArrayList with new data by calling another function. I've been reading how I shouldn't use +=, which is how I learned, because the performance is dreadful as it tears down the array and rebuilds it for each item.
The issue I have is I need to call a function to fill an empty ArrayList, but I don't seem to be able to do this inside the .Add() method.
Old code:
Function get_gfe
Function get_os
$gfe = [System.Collections.ArrayList]#()
$gfe = get_gfe
$getos = [System.Collections.ArrayList]#()
$gfe | foreach { $getos += get_os $_}
This takes over an hour to fill $getos with the data.
I was hoping to use something like this instead, but it doesn't work, any help would be appreciated
$gfe | foreach { [void]$getos.Add(get_os $_)}
I know that you can use .Add($_), but that doesn't meet my needs and I couldn't find any references to using other code or calling functions inside the .Add()method.
Thanks in advance!
Why not expand the foreach-loop to something like this:
foreach ($entry in $gfe){
$os = get_os $entry
[void]$getos.add($os)
}
A foreach-loop also saves time compared to | piping into foreach-object.
Although of course since I don't know what your functions are actually doing, this could not be the most effective way to save time. You can determine that with measure-command.
Is it absolutely vital that $getos is of type System.Collections.ArrayList instead of a 'normal' array (System.Object[]) ?
If not, I think the next code could perform faster:
$getos = foreach ($entry in $gfe) {
get_os $entry # output the result of function get_os and collect in variable $getos
}
Thanks to all for the recommendations, they've helped me to gain a better understanding of foreach, arrays, and arrayLists. We've suspect the slowness is related to the foreach loop accessing a function, which uses an API for each serial number. We had recently upgrade our MDM console and swapped out the underlying hardware.

sqlsrv_execute returning cursor I cannot return from my method

We recently upgraded our PHP version from 5 to 7 so I had to chenge the classes used to access our MS SQL database.
I started using sqlsrv and I have a method in a class to execute stored procedures which pretty much does this
<?php
$stmt = sqlsrv_prepare($db, $sql, $procedure_params);
if (!sqlsrv_execute($stmt)) {
if( ($errors = sqlsrv_errors() ) != null)
{
foreach( $errors as $error)
{
echo "SQLSTATE: ".$error[ 'SQLSTATE']."\n";
echo "code: ".$error[ 'code']."\n";
echo "message: ".$error[ 'message']."\n";
die();
}
}
}
// (1) This works, I get all the rows with data, etc...
while($row = sqlsrv_fetch_array($stmt)){
print_r($row);
}
// (2) Returning the cursos won't work, I cannot fetch it when I return it as a result
return $stmt;
?>
Once I execute the stored procedure, I get the result and I can fetch it with no problems (1). However, if I return the cursos as a result of my method / function, when I get the cursos as a result of calling the method, I cannot fetch it, it's like if it was empty. (2)
Any ideas? I'm sorry if it's a dumb question, but I have been googling for this issue and I cannot see any posts talking about a similar issue.
Thanks!
First off, why do you want to return the SQL resource? If you do that you will have a harder time closing the connection as you will need to do sqlsrv_free_stmt( $stmt); in the function you are passing back to.
Second, and I'm not a PHP expert, but I believe you are using the sqlsrv_execute which is mainly made for the one off executions with parameters such as inserts, updates and deletes. If you want to return a cursor with rows in it you will want to use sqlsrv_query.

cakephp find method not working

I know this is very silly question but here I am not getting any error.
Bellow query working fine
$data=$this->Test->query('SELECT * FROM tests where report_id=85');
But same query in find method are not working
$condition=array('Test.report_id'=>85);
$data=$this->Test->find('all',array('condition'=>$condition));
find statement in cakephp should be
$condition=array('Test.report_id'=>85);
$data = $this->Test->find('all',array('conditions'=>$condition));
Cakephp find statement error in 'codintion'
You should try this
$data=$this->Test->find('all',
array('conditions'=>
array('Test.report_id'=>85)
)
);
please replace condition to conditions
You made Typo.And lets understand why 's' is used.
There can be 100 conditions in an array , Not only one , so its conditions
$conditions=array('Test.report_id'=>85);
$data = $this->Test->find('all',array('conditions'=>$conditions));
And another thing -> Always use $conditions as variable naming convention because you never know there are 1,2, or 1000 conditions .

Perl -- DBI selectall_arrayref when querying getting Not Hash Reference

I am very new to perl (but from a c# background) and I am trying to move some scripts to a windows box.
Due to some modules not working easily with windows I have changed the way it connects to the DB.
I have an sqlserver DB and I had a loop reading each row in a table, and then within this loop another query was sent to select different info.
I was the error where two statements can't be executed at once within the same connection.
As my connection object is global I couldn't see an easy way round this, so decided to store the first set of data in an array using:
my $query = shift;
my $aryref = $dbh->selectall_arrayref($query) || die "Could not select to array\n";
return($aryref);
(this is in a module file that is called)
I then do a foreach loop (where #$s_study is the $aryref returned above)
foreach my $r_study ( #$s_study ) {
~~~
my $surveyId=$r_study->{surveyid}; <-------error this line
~~~~
};
When I run this I get an error "Not a hash reference". I don't understand?!
Can anyone help!
Bex
You need to provide the { Slice => {} } parameter to selectall_arrayref if you want each row to be stored as a hash:
my $aryref = $dbh->selectall_arrayref($query, { Slice => {} });
By default, it returns a reference to an array containing a reference to an array for each row of data fetched.
$r_study->{surveyid} is a hashref
$r_study->[0] is an arrayref
this is your error.
You should use the second one
If you have a problem with a method, then a good first step is to read the documentation for that method. Here's a link to the documentation for selectall_arrayref. It says:
This utility method combines
"prepare", "execute" and
"fetchall_arrayref" into a single
call. It returns a reference to an
array containing a reference to an
array (or hash, see below) for each
row of data fetched.
So the default behaviour is to return a reference to an array which contains an array reference for each row. That explains your error. You're getting an array reference and you're trying to treat it as a hash reference. I'm not sure that the error could be much clearer.
There is, however, that interesting bit where it says "or hash, see below". Reading on, we find:
You may often want to fetch an array
of rows where each row is stored as a
hash. That can be done simple using:
my $emps = $dbh->selectall_arrayref(
"SELECT ename FROM emp ORDER BY ename",
{ Slice => {} }
);
foreach my $emp ( #$emps ) {
print "Employee: $emp->{ename}\n";
}
So you have two options. Either switch your code to use an array ref rather than a hash ref. Or add the "{ Slice => {} }" option to the call, which will return a hash ref.
The documentation is clear. It's well worth reading it.
When you encounter something like "Not a hash reference" or "Not an array reference" or similar you can always take Data::Dumper to just dump out your variable and you will quickly see what data you are dealing with: arrays of arrayrefs, hashes of something etc.
And concerning reading the data, this { Slice => {} } is most valuable addition.

Zend Framework: count() returns 1 on empty result with findManyToManyRowset(...)

While working on a small shop application i fetch all colors of an article using Zend Framework's "findManyToManyRowset" functionality.
Example:
$colors = $article->findManyToManyRowset('Shop_Colors',
'Shop_ArticlesToColors');
Some of the articles don't have and colors assigned. I test it using count($colors) on the result of "findManyToManyRowset". But instead of the expected result "0" i get an "1" as a result, which confuses me.
Why is that ? And how can i test, if an result is empty instead ?
Thank you :)
Stephan
The findManyToManyRowset returns an object of class Zend_DbTable_Rowset. Therefore count($colors) will not return the number of rows.
The way to get the row count is:
$colors->count();
Since the count is 1, have you dumped out that $colors rowset to see what's in the rowset? Evidently something is in it.
print_r($colors->toArray());
yes, i did that. The protected array _data was empty. That's why i'm confused :)
But as you're writing this, something comes to my mind. I changed the methode "toArray" in the color's rowset class to fit my needs (changed formatting of the data). Maybe that is the problem ?
public function toArray() {
$toArray = array();
if (count($this->_data) > 0) {
foreach ($this as $row) {
$toArray[$row['color_id']] = $row['color'];
}
}
return $toArray;
}

Resources