[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 118
  • Last Modified:

memory errors using foreach loops

I have a PHP file that uses the NuSOAP toolkit to connect to an API and return records that I then write to a local database.  I'm getting memory errors long before every record is returned.

The first problem - I'm not awesome at PHP.

I've read about foreach loops not being memory friendly and that I should be using for loops instead.  But (referencing 'the first problem'), I need a little help.

Anybody want to help me get this file to run without throwing memory errors (and maybe make it a little more efficient in the process)?

Thanks,
Todd
get-JournalEntries.php
0
Carlos Elgueta
Asked:
Carlos Elgueta
  • 4
  • 3
2 Solutions
 
GaryCommented:
One potential problem I see is that you are creating a new db connections for every loop in your foreach

Another thing to look at would be using prepared statements
http://php.net/manual/en/mysqli.prepare.php
0
 
Carlos ElguetaAuthor Commented:
I've removed the db connections.  Will the statement preparations really help reduce memory?

One thing if tried is replacing

foreach ($response['data'] as $data)

Open in new window


with
$record = $response['data'];
foreach ($record as $data)

Open in new window


Because I had read it could improve memory when using foreach loops.
0
 
GaryCommented:
With the prepared statement the sql is sent to the sql server then in your loop you are just sending the data to use in the sql so it should be a lot faster and use less memory.

Your code above makes no difference really.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Carlos ElguetaAuthor Commented:
Ok - I'll give it a shot.  The code above was in reference to a blog re: a memory leak in PHP 5 foreach loops - just figured I'd try it.
0
 
GaryCommented:
How many records are you inserting here?
And remember using Frameworks is alway memory hungry
0
 
Carlos ElguetaAuthor Commented:
I've requested that this question be deleted for the following reason:

No longer need an answer...
0
 
Carlos ElguetaAuthor Commented:
Thanks for your help.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now