flint
flint

Reputation: 345

PHP While loop not finishing after nested foreach finishes

The outer while loop never resumes after the inner foreach loop finishes. When the inner finishes the file reports back to the command as if it has completed. It never echos "+++++++".

The script is meant to pull some data from an api and save that data to a table, the api returns records in batches of 1000 so the outer while loop pulls multiple sets of 1000. The script returns 'Saved' alot of times but never the '++++++'. Any ideas?

while ($iterations > 0) {

        $results = json_decode(file_get_contents("http://foo.bar?start=$start$limit=1000"), true);

        foreach ($results['SearchResult']['Records'] as $result) {

                //search table
                $query = "SELECT id from sometable where name = '".$result['something']."'";
                $res = mysql_query($query, $conn) or die(mysql_error());
                $branch = mysql_fetch_assoc($res) or die(mysql_error());

                //save to table
                $query = "INSERT INTO `table` some values)";
                if (mysql_query($query, $conn) or die(mysql_error())) {
                    echo 'SAVED';
                }   


        }
        $start = $start+1000;
        $iterations--;

        echo "++++++++++++++++++++";
    }

Upvotes: 0

Views: 294

Answers (1)

showdev
showdev

Reputation: 29168

This may be causing problems:

if (mysql_query($query, $conn) or die(mysql_error())) {

The die() command is processed as part of your if statement.

Instead, I'd do something like this:

$q=mysql_query($query, $conn) or die(mysql_error());
if ($q) {

Upvotes: 3

Related Questions