0

I am trying to insert multiple rows based on a loop.
This code inserts the first item from the loop only, then ignores the rest of the loop
I know the loop is counting correctly as echo'ing out the values outputs ok

$i = 1;
while ($i <= $count){

    foreach($html->find('.markuptag a') as $mystring){
        if(preg_match_all("|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i", $mystring, $matches)){
            $a = $matches[2][0];
         }

        $query = "INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES ('$fistname', '$lastname', '$a')";

        $mysqli->query($query);//<< is there a better way?

    }
    $i++;
}

1 Answer 1

5

Build an array of the rows to insert, then insert them all at once. Something like this:

$arr = []; // array() in PHP 5.3 and older
foreach(...) {
    ...
    $arr[] = "('$fistname', '$lastname', '$a')";
}
$mysqli->query("INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES "
    .implode(",",$arr));
Sign up to request clarification or add additional context in comments.

2 Comments

how would this work if i need to capture the $thisID = $mysqli->insert_id of each of the arr?
Hmm... You could get that ID still, it should be the ID of the last row inserted, then subtract count($arr)-1 to get the ID of the first, and work from there.

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.