How can I avoid Duplicate Registration in MySQL?

0

I'm trying to make a validation to avoid that the user or users avoid double posts, that is to say that the mail data in the user table within MYSQL PHPMYADMIN does not repeat, my code is as follows


<?php
	require_once "Conexion.php";
	require_once "UsuarioFotoDocumento.php";

	$obj=new documento();

	$datos=array();

	/*--EN ESTA PARTE SE AGREGA EL POSTEO DE LA IMAGEN QUE SOLO ALMACENA LA DIRECCION DE LA CARPETA*/
	$nombreImg=$_FILES['imagedoc']['name'];
	$RutaAlmacenamiento=$_FILES['imagedoc']['tmp_name'];
	$carpeta='../../archivos/';
	$RutaFinal=$carpeta.md5(rand() * time()).$nombreImg;
	/*--Y SE GUARDA, DECLARANDO INICIO DE LA RUTA Y FINAL DE LA MISMA CREANDO UNA CARPETA ARCHIVOS*/
  
$datosImg=array(
  $_POST['iTipDocIdent'],
  $nombreImg,
  $RutaFinal
    );

  if (move_uploaded_file($RutaAlmacenamiento, $RutaFinal)) {
   $idimagen=$obj->agregarImagenDoc($datosImg);

   if (buscaRepetido( $datos[1],$conexion) == 1) {
    echo 2;
   }else {
   if ($idimagen > 0) {

    $datos[0]=$_POST['iCodOrdenante'];
    $datos[1]=$_POST['vEmailUsuario'];
    $datos[2]=sha1($_POST['vPassUsuario']);
    $datos[3]=$_POST['iTipDocIdent'];
    $datos[4]=$idimagen;

     echo $obj->insertarUsuarioNuevo($datos);
    }else {
     echo 0;
    }    
   }
  }

  function buscaRepetido($email,$conexion){
   $sql="SELECT * from tbl1_usuario
        where vEmailUsuario='$email'";
   $result = mysqli_query($conexion,$sql);

   if (mysqli_num_rows($result) > 0) {
            return 1;
           }else{
            return 0;
           }        
  }
?>

I'm using a AJAX where you should register the data plus an image in my function ajax declines me to error and that's because of the arrangement because before putting the function of searchRepeats I registered the data and the normal image without problems, someone knows if the order of the function is affecting the arrangement for which it does not register, in my file of arrangement are 2 the first one is the one that arrives and the second is to collect the data and store them in data array variables by row that is $ data [0] since I can register in my two tables one that is the user record table and the other table of the user's image where both tables are related by user ID_IMAGEN I leave my second arrangement that goes hand in hand with the adduser fix

<?php 
	class documento{
		public function agregarImagenDoc($datos){
			$c=new conectar ();
			$conexion=$c->conexion();

			$fecha=date('Y-m-d');

			$sql="INSERT into tbl4_img_cliente (id_iTipDocIdent,
														Nombre_Img,
														Ruta_Img,
														fechaSubida)
														values ('$datos[0]',
																'$datos[1]',
																'$datos[2]',
																'$fecha')";

			$result=mysqli_query($conexion,$sql);

			return mysqli_insert_id($conexion);
		}

		public function insertarUsuarioNuevo($datos){
			$c=new conectar ();
			$conexion=$c->conexion();

			$sql="INSERT into tbl1_usuario (iCodOrdenanteCli,
															vEmailUsuario,
															vPassUsuario,
															iTipDocIdent,
															vFotoCliente_ID)
								values ('$datos[0]',
										'$datos[1]',
										'$datos[2]',
										'$datos[3]',
										'$datos[4]'";			

			return mysqli_query($conexion,$sql);										
		}
	}
 ?>

Lastly, this is my AJAX code, in case the doubts here is where the data and the image go through MULTIPART

var formData = new FormData(document.getElementById("User_Form_Reg"));

				$.ajax({
					url: "AgregarNuevoUsuario.php",
					type: "post",
					dataType: "html",
					data: formData,
					cache: false,
					contentType: false,
					processData: false,

					success:function(r){
						
            if (r==2){
            alert.('Correo repetido');
            }
						elseif(r == 1){
							alert.('Registro Exitoso');
							$('#User_Form_Reg')[0].reset();
						}else{
							alert.('Error');
							return false;
						}
					}
				});
    
asked by 12.08.2018 в 22:41
source

2 answers

3

A good practice is to create a unique index for the mail of the users who want to register, I leave you a create example of the table in MySQL:

CREATE TABLE 'users' (
    'id' INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    'name' VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
    'user_name' VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
    'email' VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
    'password' VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
    'rol' INT(11) UNSIGNED NOT NULL DEFAULT '2',
    'remember_token' VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
    'created_at' TIMESTAMP NULL DEFAULT NULL,
    'updated_at' TIMESTAMP NULL DEFAULT NULL,
    PRIMARY KEY ('id'),
    UNIQUE INDEX 'email' ('email')
)

If you look at this line, it is where you add:

UNIQUE INDEX 'email' ('email')

This way, when you try to add an existing email, it would throw you an error.

    
answered by 13.08.2018 в 00:48
0

Eduardo Díaz's option would be the best, but you could also use a SELECT that will look for the mail in the table and if you throw a record, you send an error message and you do not do the INSERT, otherwise, you execute the INSERT I leave you an example:

$correo = mysql_num_rows(mysql_query("SELECT * FROM tbl1_usuario WHERE 
correo='$datos[*correo*]'"));
if($correo==0){
*código del INSERT*
}else{
echo 'Ya existe un usuario registrado a este correo';
}

There are many ways of doing things, as I said, Eduardo Días gave a better alternative, but I'll leave you here another way.

    
answered by 13.08.2018 в 01:04