Home > Blockchain >  PHP file_get_contents with multiple urls
PHP file_get_contents with multiple urls

Time:11-18

So basically what I'm trying to do is for each row that has been generated by the query, I try to generate a URL and visit that URL. The funny part is that it always only visits the FIRST generated URL and never visits the others.

What am I doing wrong? Please help me.

$query = "SELECT distinct b.productname, b.seller, b.price, b.offerid 
          from tracker b";
$results = mysqli_query($dbcon, $query);

$rows = array();
$i = 0;

while ($row = mysqli_fetch_assoc($results)) {
    $rows[] = $row;

    foreach ($rows as $row) { 
        $url = 'url'.$i;
        $$url = 'https://bla.com/tools/tracker.php?productID=' .
                $row["productname"] . '&verkoper=' . 
                $row["seller"] . '&offerid=' . 
                $row["offerid"] . '&price=' . $row["price"] . 
                '&productTracken=';

        // set URL and other appropriate options
        file_get_contents($$url);

        $i  ;
    }
}

CodePudding user response:

If you simplify what you are doing you may get the result you want

All you seem to be doing is touching a list of urls built from data in a table

Also you dont need a while loop and a foreach loop, that is what is definitely causing your problems.

$query = "SELECT distinct b.productname, b.seller, b.price, b.offerid 
          from tracker b";
$results = $dbcon->query($query);

while ($row = $results->fetch_assoc()) {

    $url = 'https://bla.com/tools/tracker.php?productID=' .
                $row["productname"] . '&verkoper=' . 
                $row["seller"] . '&offerid=' . 
                $row["offerid"] . '&price=' . $row["price"] . 
                '&productTracken=';

    // set URL and other appropriate options
    file_get_contents($url);
}

CodePudding user response:

You have a couple of odd things happening here.

First, your loops:

while ($row = mysqli_fetch_assoc($results)) {
    $rows[] = $row;

    foreach ($rows as $row) { 

Each time you fetch a row from the database, you add it to an array. You then immediately loop over all the items in that array. If you output a row number each time, you'd get 0; then 0, 1; then 0, 1, 2; and so on.

Secondly, your URL variable:

$url = 'url'.$i;
$$url = 'https://...';

This uses an esoteric feature of PHP called variable variables: you choose dynamically what variable name you want. This feature is basically never needed, because it's almost always better to use an array:

$urls[$i] = 'https://...';

In this case, though, you're only using one value at a time, so you can just use a plain old variable:

$url = 'https://...';

Fixing these gives you the code in RiggsFolly's answer, and will probably fix your problem.

  • Related