简体   繁体   English

for循环内的mysql查询未插入所有值

[英]Mysql query within for loop not inserting all values

I have the following for loops, which should insert values into a mysql table. 我有以下for循环,应将值插入mysql表中。 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. 有一个用户数组,它遍历数组和计算统计信息,它应该将所有值插入mysql表中,但它只插入在用户数组的第一个元素上完成的操作,而不是其余部分。 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循环,仅插入了第二个for循环,尽管我可以看到这些循环正在执行他们应该做的事情,只是没有将其插入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. 在for循环中生成它,并一次调用mysql查询。

You can check if your generated query works simply by echo it before execute and try to run it using some sql client. 您可以通过在执行之前回显它来检查生成的查询是否工作,然后尝试使用某些sql客户端运行它。

try this, 尝试这个,

$sql = "INSERT IGNORE into dat_net VALUES ('{$user1}','{$user2}','{$union}','{$intersect}','{$rate}')";

But it will be good if you create a insert query in foreach loop and then fire it once after completing foreach loop. 但是,如果您在foreach循环中创建一个插入查询,然后在完成foreach循环后将其激发一次,那将是很好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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