每当提交重复条目时,我都会尝试验证并向用户显示一条消息。此外,每当用户首次注册时,我都会使用此验证在我的数据库中生成一个条目。我知道我的代码可能受到 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/