2017-06-22 23 views
2

我試圖驗證並顯示一條消息給用戶,只要提交重複條目。另外,每當用戶首次註冊時,我都會使用此驗證在我的數據庫中生成一個條目。我知道我的代碼可能是SQL注入漏洞,但我並不擔心這個練習。如何使用PHP驗證SQL中的重複條目?

我的表有一個主鍵「RUT」,它是唯一的。我需要驗證用戶是否已經在數據庫中提交RUT。

代碼:

$datos; 

    @$db = mysqli_connect("localhost","root","","speedomart"); 

    if($db){ 
     $sql = "insert into cliente values('".$rut."','".$nombre."','".$apellido."','".$correo."','".$pass."')"; 
     $query = $db->prepare($sql); 
     $query ->execute(); 
     if(mysql_errno() == 1062){ 
        $datos = array('mensaje' => "no fue posible insertar datos"); 
        echo json_encode($datos); 
     } 
     else{  
       $sql2 = "insert into carrito values(NULL,'".$rut."')"; 
       $query = $db->prepare($sql2); 
       $query ->execute();  
       $datos = array('mensaje' => "Registrado correctamente"); 
       echo json_encode($datos); 
      }; 
    } 
    else{ 
      $datos = array('mensaje' => "No hay conexion."); 
      echo json_encode($datos); 
    }; 
+1

添加跨越多個列的唯一索引。 – Scuzzy

+0

可能重複[避免重複進入mysql數據庫的最佳方法](https://stackoverflow.com/questions/2219786/best-way-to-avoid-duplicate-entry-into-mysql-database) – Scuzzy

+0

可能的重複[插入插入前檢查重複的語句](https://stackoverflow.com/questions/8312058/insert-statement-that-c​​hecks-for-duplicate-before-insert) –

回答

0

我假設它是不能重複的電子郵件。因此,當您提交表單,您可以使用特定的電子郵件ID如下首先選擇數據:

$sql = "select *from table where email ='".$email."'"; 
      $query = $db->prepare($sql); 
      $user_array = $query ->execute(); 

    if(count($user_array) > 0){ 
     //You can use insert query here 
    }else{ 
     //email already exist. 
    } 
0
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN 
    --record exists, get ID you need. 
    BEGIN 
    SELECT TableID FROM Table WHERE FieldValue=''; 
    END; 
ELSE 
BEGIN 
    INSERT INTO Table (FieldValue) VALUES(''); 
    SELECT LAST_INSERT_ID() AS TableID; 
END; 
END IF;