Prevent duplicate registration with PDO

Asked

Viewed 979 times

2

I’d like to prevent the same source from registering for duplicities. The code used for registration is below:

<form name="enter" method="post" action="" enctype="multipart/form-data">
<?php if(isset($_POST['enter'])){
$font = $_POST['font'];
$pdo = new PDO('mysql:host=localhost;dbname=site', "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare ('INSERT INTO fontes (font) VALUES (:font)');
$stmt->execute(array(':font' => $font));

echo "<meta http-equiv='refresh' content='0; URL= ../cadastros/cad_fonte.php'>
<script language='javascript'>
window.alert('Fonte Cadastrada com sucesso!');
</script>";
}
?>

<h3>Caso a fonte desejada não esteja listada, cadastre-a agora!</h3><br />
<input type="text" name="font" value="" />
<input class="input" type="submit" name="enter" value="Cadastrar" />

How could avoid that the person register a source already registered in the BD.

  • An index UNIQUE in your field, would solve the problem... or would you like otherwise?

1 answer

1


You can use Count to check if it already exists in the bank!

    if( $pdo->query("select count(*) from fontes where font = '{$font}'")->fetchColumn() <=0) {

        $stmt = $pdo->prepare ('INSERT INTO fontes (font) VALUES (:font)');
        $stmt->execute(array(':font' => $font));

        echo "<meta http-equiv='refresh' content='0; URL= ../cadastros/cad_fonte.php'>
        <script language='javascript'>
            window.alert('Fonte Cadastrada com sucesso!');
        </script>";

    } else {        
        //Tratar o erro aqui        
    } 
  • Thanks Williams, it worked great, Big Brother.

  • @Murilocabral, mark the answer as correct.

Browser other questions tagged

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