How to check if data already exists or has been left blank?

2

I was testing the site registrations I made, and I noticed that I was able to register the same username twice, even though I declared "UNIQUE" in the table.

And another thing, I also noticed that although I left the fields obligatory, in case someone type space, the registration is done successfully. How do I prevent something like this from happening?

Below is the insertion code in the database:

<?php

// captura dos dados digitados no formulário //
$nome=$_POST ['nome'];
$sobrenome=$_POST ['sobrenome'];
$username=$_POST ['username'];
$email=$_POST ['email'];
$senha=$_POST ['senha'];
$telefone=$_POST ['telefone'];

$sql = mysql_query("INSERT INTO cadastro (nome,sobrenome,username,email,senha,telefone)  VALUES ('$nome', '$sobrenome','$username','$email','$senha','$telefone')") or die(mysql_error());

$resultado = mysql_query ($sql);
header ("Location:../usuario/index.php");
?>
    
asked by anonymous 13.10.2018 / 18:52

2 answers

1

this same insert with pdo would look like this with the removal of spaces

$host = "localhost";
$user = "seu usuario";
$pass = "sua senha";
$banco = "seu banco de dados";

$conn = new PDO('mysql:host='.$host.';dbname='.$banco.'',$user,$pass);

if(empty($_POST['username'])){
    echo "Username vazio!";
}else{
   $nome = $_POST['nome'];
   $sobrenome = $_POST['sobrenome'];
   $username = trim($_POST['username']);
   $email = $_POST['email'];
   $senha = $_POST['senha'];
   $telefone = $_POST['telefone'];

   $insere = $conn->prepare("INSERT INTO cadastro (nome,sobrenome,username,email,senha,telefone)  VALUES ('$nome', '$sobrenome','$username','$email','$senha','$telefone')");
   $insere->execute();


   if($insere){
      echo "Inserido com sucesso!";
   }else{
      echo "Erro ao inserir!";
   }
}
    
13.10.2018 / 21:13
1

Removing the spaces

If you are validating in Javascript with Jquery, you can do the following:

var nome = $('#nome').val().trim(); // O método trim remove os espaços

if(nome === ''){
    alert('Preencha o nome!');
}

To remove spaces in PHP, there is the trim function:

// Com trim os espaços são removidos das strings
$nome      = trim($_POST['nome']);
$sobrenome = trim($_POST['sobrenome']);
$username  = trim($_POST['username']);
$email     = trim($_POST['email']);
// Aqui seriam colocados o restante dos campos...

Preventing duplicate inserts in the database

To avoid duplication, you need to verify that the record exists before you enter it. That is, you need to do a query to check if the username has already been entered before. The username field is what I am using as an example, if it is another field that will define if the user is unique, just use it instead of username.

The query would look like this:

"SELECT id FROM tabela WHERE username = '$username' LIMIT 1"

If the query returns results, it means that the user already exists, knowing this just verify the result before doing the insert. Remember that "table" should be replaced with the name of the table you are using in your database.

PS: I recommend you use the PDO because the mysql_ * functions are deprecated. I also recommend filtering the data sent by POST, so there is PHP's filter_input function.

    
13.10.2018 / 20:15