Monday, 3 September 2018

Query Mysql in the for loop for not inserting all values

I have the following for loops, which should insert values into a mysql table. There is a users array and it is looping over the array and calculation statistics, and it should be inserting all the values into the mysql table, but it only inserts the operation done on the first element of the users array and not the rest. It is ignoring the first for loop, and only inserts for the second for loop, even though, I can see that the loops are doing what they are supposed to do, it is just not being inserted into mysql.

for($i=0; $i<count($users); $i++)
{
    for($j=$i+1; $j<count($users); $j++)
    {
        $user1=$users[$i];
        $user2=$users[$j];
        $dat1=getData($user1);
        $dat2=getData($user2);
        $union=count(array_unique(array_merge($dat1, $dat2)));
        $intersect=count(array_intersect($dat1, $dat2));
        $rate=$intersect/$union;
        $sql = "INSERT IGNORE into dat_net VALUES ($user1,$user2,$union,$intersect,$rate)";
        $sqlresults = mysql_query($sql);
        echo " ".$user1." ".$user2." \n";
        if ($sqlresults === false) {
    // An error has occured...
    echo mysql_error();
}

    }

}

Solved due to tips in the comments: I had inadvertently set up keys for the columns, so it wasn't inserting due to duplication.

First of all insert all data using one query. Generate it in for loop and call mysql query once.
You can check if your generated query works simply by echo it before execute and try to run it using some sql client.

0 comments:

Post a Comment