简体   繁体   中英

PHP Function is only called once in for loop

I am sure that this question has been asked before, but I am unable to come up with the proper keywords (especially in english).

I am using PHP and I am trying to for loop through a parameter of a function. So the function should be called, store the retrieved data in some variables and these variables should then be inserted into a database.

However, the loops only runs once! If I substitute $id with any number it works fine, but only once.

This is a simplified version of my code:

for ($i=0; $i<9; $i++) {
    $id = $rows[$i][1];
    $values = getDetails($id); // This function (from another file) returns an array

    $title = $values["Title"];
    $year = $values["Year"];

    $query=  " INSERT INTO database
        VALUES ('','$title','$year')";
    $result = $mysqli->query($query);
}

* EDIT This is part of the getDetails function:

function getDetails($id) {

$url = "http://www.something.de/". $id . "/";
$html = file_get_html ( $url );
$title = $html->find('span[itemprop=name]');
$title = explode('>',$title[0]);
$title = explode('</span',$title[1]);

... // This might look weird and is definatly not perfect, but it works :)

$details = array("Title" => $title[0], "Year" => $year[1]);
return $details;
}

* EDIT WOW! I found the reason ... I had a function within my function which was never used. I just commented it out and my code works just fine. I assume it is not a good idea to so anyways.

I think your $query is wrong.

Change this:

$query=  " INSERT INTO database
        VALUES ('','$title','$year')";

To something like this:

$query=  " INSERT INTO database (field1,field2,field3)
        VALUES ('','$title','$year')";

Is your ID field autoincrementing? If so you do not need the "field1" entry at all.

Happy Coding!

I had this problem also.

I could print to a table without a problem the parameters I was feeding into a function in a loop. But the function calls in the loops would only call once.

SOLUTION: Remove the location redirects and the exit(); from the function.

Hope this helps someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM