s_p
s_p

Reputation: 4693

mysqli insert multiple rows from a loop

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++;
}

Upvotes: 0

Views: 1312

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

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));

Upvotes: 5

Related Questions