Prevent duplicate registration with PDO

1

I would like to prevent duplicate registration of the same source. The code used for registration is the one 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 you prevent the person from registering a source already registered in the database.

    
asked by anonymous 13.05.2015 / 15:12

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        
    } 
    
13.05.2015 / 15:50