在插入数据已经存在或不存在之前进行检查

时间:2019-01-30 06:26:22

标签: php mysql

当我第一次单击第二次插入新数据时,单击那一次不检查

function post($payload)
{   
    $stmt = $this->db->prepareQuery("SELECT * FROM user WHERE emailId= ? or phone= ?");
    $stmt->bind_param('ss', $payload->email, $payload->phone);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($rows=$result->fetch_assoc()) 
    {
        if($rows['emailId']!=$payload->email || $rows['phone']!=$payload->phone)
        {           
            $stmt = $this->db->prepareQuery("insert into user(emailId,phone,name,city,category_id,password) values(?,?,?,?,?,?)");
            $stmt->bind_param('ssssds', $payload->email, $payload->phone, $payload->name, $payload->city, $payload->categ, $payload->pwd);
            $stmt->execute();
            $stmt->close();
            $this->db->commit();
            return $payload;            
        }
        else
        {
            $stmt->close();
            echo "Already existed"; 

            return $payload;
        }
    }
}           

1 个答案:

答案 0 :(得分:1)

您正在检查记录,就像您知道记录将在第一行中一样。如何引入另一个变量说$duplicate

     $duplicate = false;
 while ($rows=$result->fetch_assoc()) 
 {
    if($rows['emailId']==$payload->email || $rows['phone']==$payload->phone)
    {           
        $duplicate = true;
        break;          
    }


  }

 if(!$duplicate){
   $stmt = $this->db->prepareQuery("insert into 
   user(emailId,phone,name,city,category_id,password) values(?,?,?,?,?,?)");
   $stmt->bind_param('ssssds', $payload->email, $payload->phone, $payload->name, 
   $payload->city, $payload->categ, $payload->pwd);
   $stmt->execute();
   $stmt->close();
   }
  else{
    echo "Duplicate";
  }