Check if information already exists in the database

Asked

Viewed 1,577 times

-1

Good people try to help me out here

Html part

<form method="post" id="formulario" action="dados.php">  
   <p><label>Nome</label><input type="text" class="nome" name="nome" size="60" /></p>  
            <div id="telefone">  
        <p><label>Telefone</label><input type="text" class="fone" name="fone[]" size="15" /><span class="adicionar">Adicionar telefone</span></p>  
   </div>  
        <p><input type="submit" value="Enviar" id="btEnviar" name="btEnviar" />  
 </form> 

Part php

<?php  

$ligacao = mysqli_connect("localhost", "root", "", "teste");
                        if (mysqli_connect_errno()) {
                            echo "Erro na liga??o MySQL: " . mysqli_connect_error();
                        }


$nome=$_POST["nome"];





foreach($_POST['fone'] as $fone)  
{


    $inf = "select nome, tel from teste where nome = '".$nome."'";
    $res=mysqli_query($ligacao,$inf);

    while( ($registo = mysqli_fetch_assoc($res)) !=null)
   {

                $infoNome=$registo["nome"];
                $infoTel=$registo["tel"];
                echo $infoNome;
                echo $infoTel;
   }


   if ($infoTel==$fone){

   }
   else{
     $sql = "insert into teste (nome, tel) values ('$nome' ,'$fone')";
     $resultado = mysqli_query($ligacao,$sql);
}  
}
?>

What I want to do is that in the php part when analyzing all the numbers of cell phone that the person enter that will compare and if already exists in the database does not let add again

inserir a descrição da imagem aqui

To be easier to visualize if I were to input these numbers I wanted you to just input 345, 234 and 123 once, but that’s not what’s happening and I can’t figure out why

  • 1

    Phones cannot be repeated in the database, right? A good alternative is to turn the test.tel column into UNIQUE. This will generate an error when entering the data by PHP.

1 answer

1

Well, I’m not sure how mysqli works, so I will display a practical method that I would use using the UNIQUE that Bruno said there, I’ll do in PDO, but you adapt to your way!

$fone = $_POST["fone"]; //recebe o post
$fone = array_unique($fone); //elimina array duplicadas
foreach($fone as $f){ //salva tudo no BD
        $this->databaseConnection();
        $prepara = $this->db_connection->prepare('INSERT INTO seubanco (telefone) VALUES (:telefone)');
        $prepara->bindValue(':telefone', $f, PDO::PARAM_STR);
        $prepara->execute();
}

With the past explanation, all I could think about!

I hope it helps you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.