php - 如何使用 PHP 验证 SQL 中的重复条目?

标签 php mysql

每当提交重复条目时,我都会尝试验证并向用户显示一条消息。此外,每当用户首次注册时,我都会使用此验证在我的数据库中生成一个条目。我知道我的代码可能受到 SQL 注入(inject)攻击,但在本练习中我并不担心。

我的表有一个主键“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);
    };

最佳答案

我假设这是不能重复的电子邮件。因此,当您提交表单时,您可以首先使用特定的电子邮件 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.
    }

关于php - 如何使用 PHP 验证 SQL 中的重复条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689432/

相关文章:

php - 在Docker容器中使用php-fpm的ORA-28547

mysql - Django ORM : Tried to do inner join with foreign key but causes FieldError

php登录代码,数据不匹配

mysql - 需要优化这个查询

php - 强制用户选择至少一个复选框 - Laravel

PHP 有什么比curl 更快的方法来检查远程图像文件大小大约3000 倍?

mysql - phpMyAdmin 高级功能问题

mysql - 如何在 mysqlsh importTable util 中设置 IGNORE 标志?

java - 在一个 PHP 中,android 尝试发送多种 json 格式,但只收到一种。我应该怎么办?

php - mysql 三个表的内连接和外连接