search

Home  >  Q&A  >  body text

mysql - The problem of repeated entry always occurs in PHP loops

Store the user information in an array, and then use a loop to enter the mysql database. However, occasionally the information of individual users will be entered twice. I don’t know where the logic error is. Please give me some advice:
The logic code is as follows

$data = array(); //用户信息数组
for($i=0;$i<count($data);$i++){
    $sql = "INSERT INTO *********";
    $result = mysql_query($sql);
    
    //以下是录入统计成功与失败的数量
    if($result){
          $success_num[]=$i;
        }else{
          $error_num[]=$i;
        }
}

//跳出循环,弹出结果给用户,并跳转到首页

$con = "成功上传".count($success_num)."条!-  失败:".count($error_num)."条";
echo "<script> alert('$con');parent.location.href='index.php'; </script>";

What is strange at the moment is that the information entered by individual users is always executed twice (for example, the submitted array only has 5 elements, but the entry into the database produces 10 records)

90% of the entries are normal, only some users will do it, please give some guidance

PHP中文网PHP中文网2784 days ago619

reply all(4)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-24 11:32:40

    This happens when you use location.href to jump. Some browsers may re-submit the form twice as soon as they are refreshed. There are several solutions. I will just give you an example.

    1. ajax no refresh

    2. When the front-end submits, the back-end generates a token and saves it to the session. When submitting to the back-end, the two tokens are compared

    3. Database for verification

    4. The backend uses 301 or 302 to jump

    5. reply
      0
  • 巴扎黑

    巴扎黑2017-05-24 11:32:40

    I don’t see any special problems logically. I can only say that it may be that your front-end submitted two requests, and generally speaking, when inserting data, it is generally judged whether the user exists in the database, but you did not make this judgment, which also caused the information to appear. Ten records

    reply
    0
  • 为情所困

    为情所困2017-05-24 11:32:40

    What you should think of is:

    insert into table (fields...) values(values),(values),(values);

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-24 11:32:40

    Before inserting, judge the value of the database, at least with a unique index.

    In case of individual input errors, it depends on the data in your $data.

    reply
    0
  • Cancelreply