Home > OS >  PREVENT DUPLICATION for INSERTING DATA in PHP MySQL
PREVENT DUPLICATION for INSERTING DATA in PHP MySQL

Time:01-05

Good Days I am new at programming and I have a problem I want to prevent duplication. What do I need to Add in my code just to prevent duplication when inserting a data ( just only in the "NAME" on my table).


    if(isset($_POST['text'])){

        $text =$_POST['text'];

        $sql = "INSERT INTO table_attendance(NAME,TIMEIN) VALUES('$text',NOW())";
        if ($conn->query($sql) ===TRUE) {
            $_SESSION['success'] = 'Action Done';
        }else{
            $_SESSION['error'] = $conn->error;
        }

        header("Location: index.php");
    }
    $conn->close();

What do I need to add in my code so it wont accept same NAME and prevent duplication

CodePudding user response:

  1. Add a UNIQUE KEY in MySQL on the name column.

  2. Change your INSERT INTO table_attendance... to INSERT IGNORE INTO table_attendance....

Please note that your code is currently susceptible to SQL injections.

This is very dangerous. Be sure to not deploy such code when launching an actual product.

See more info here: How does the SQL injection from the "Bobby Tables" XKCD comic work? .

  • Related