2

I have been having a problem with my PHP loop described below.

$query1 = "SELECT * FROM volume_issue";
$sql=$con->prepare($query1);
$sql->execute();

while ($row = $sql->fetch()) {
    //echo $row['id'] . "&nbsp". $row['url']."<br />\n";
    $volume_issue_id = $row['id'];
    $url = $row['url'];
    $volume_issue = $row['volume_issue'];
    $html2 = file_get_html($url);
    //
    //echo $url . '<br>';
    $html = file_get_html($url);

    foreach($html->find('table[class="tocArticle"]') as $div){
        //echo $div->innertext . '<br>';
        //echo "<p/>". $div->nodeName. ": ";
        foreach($div->find('td[class="tocTitle"]') as $td){
            //echo $td . "<br />";
            foreach ($td->find('a') as $links){
                $url =$links->href;
                $title = $links->innertext;
                echo $title . '<br>';
                $query1 = "INSERT INTO citations_url (title,url) VALUES (:title,:url)";
                $sql=$con->prepare($query1);
                $sql->execute(array(
                                  ':title' => $title,
                                  ':url' => $url
                                  ));


            }

        }

    }
}

The problem is that this loop is only inserting 20 rows instead of 615. Also, When I remove the MySQL query and echo out $title i get 615 rows. However, when I include the MySQL query and echo out $title i get 20 rows and only 20 rows are inserted.

I have been cracking my head over this one. What might I be doing wrong?

6
  • please share your complete source code. Commented Aug 3, 2018 at 7:31
  • I would make an array, filling it up in the loop and then make one query to insert all data. Commented Aug 3, 2018 at 7:31
  • I have included the complete sourcecode as requested by @coder001. One url in the table volume issue is an array of multiple urls. Commented Aug 3, 2018 at 7:36
  • 3
    @Msela You have 2 variables with name $sql: at the top and in the inner loop. Try renaming the 2-nd to $sql1. Commented Aug 3, 2018 at 7:40
  • $sql is getting overwritten in the inner loop. which is why the 1st loop does not execute the next time it comes out of the inner loops. Commented Aug 3, 2018 at 7:48

1 Answer 1

3

You have 2 variables with name $sql: at the top and in the inner loop. Most probably after you finish INSERT query, the 2-nd call to $sql->fetch() doesn't work.

Try renaming the 2-nd variable, so they won't overlap.

Sign up to request clarification or add additional context in comments.

1 Comment

After changing $sql to $sql1 as suggested by @user4035 the problem was solved.Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.