Uchiha Obito
Uchiha Obito

Reputation: 69

Using nested loops to call cURL endpoints and insert response rows in database

I want something like this:

$i = 1;
$y = 1;

while ($i <= 10 and $y <= 5) {
    if ($i == 10) {
        echo 'I = ' . $i . ', Y = ' . $y . '<br>';
        $i = 1;
        $y = $y + 1;
    } else {
        echo 'I = ' . $i . ', Y = ' . $y . '<br>';
        $i = $i + 1;
    }
}

Which returns

I = 1, Y = 1
I = 2, Y = 1
....
I = 1, Y = 2
I = 2, Y = 2
....
I = 1, Y = 3
I = 2, Y = 3

etc, etc, to use with cURL. But it doesn't work. What am I doing wrong?

$i = 1;
$y = 1;

while ($y <= 9) {
    while ($i == 499) {
        if ($connection = db_connect()) {
            $post = array(
                'something' => 'abc',
                'value_of_y' => '' . $y . '',
                'value_of_i' => '' . $i . ''
            );
            $str = curl_grab_page('http://localhost/send.php?true=1', '', 'off', $post);
            $str2 = mysql_real_escape_string($str);
            $sql = "INSERT INTO abc (txt) VALUES ('$str2')";
    
            $i = 1;
            $y = $y + 1;
        } else {
            echo 'Database connection error!';
        }
    }
    while ($i != 499) {
        if ($connection = db_connect()) {
            $post = array(
                'something' => 'abc',
                'value_of_y' => '' . $y . '',
                'value_of_i' => '' . $i . ''
            );
            $str = curl_grab_page('http://localhost/send.php?true=1', '', 'off', $post);
    
            $str2 = mysql_real_escape_string($str);
            $sql = "INSERT INTO abc (txt) VALUES ('$str2')";
    
            $i = $i + 1;
        } else {
            echo 'Database connection error!';
        }
    }
}

But the page keeps loading and nothing happens. I have to use if($connection = db_connect()){, but I think this is what keeps messing up my code.

Upvotes: 0

Views: 281

Answers (2)

Bart Friederichs
Bart Friederichs

Reputation: 33521

My solution would be as follows:

$y = $x = 1;

if (!$connection = db_connect()) {
   echo "connection failed!";
} else {
   while ($y <= 9) {
     $x = 1;
     while ($x <= 499) {
       // do your things with $x and $y, don't forget mysql_query() !

       $x++;   
     }
     y++;
   }
 }

Upvotes: 2

NewInTheBusiness
NewInTheBusiness

Reputation: 1475

Maybe this is a start?

$sql = "INSERT INTO abc (txt) VALUES ('".$str2."')";

Upvotes: -1

Related Questions