0

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

1 Answers1

0
  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? .

obe
  • 7,378
  • 5
  • 31
  • 40
  • but the problem is the auto increment, the numbering is continues even the data is not accepted – Arth Quilitis Jan 05 '23 at 01:15
  • 3
    @ArthQuilitis Why is that a problem? Forget the idea that the autoincrment ID should be sequential. That's not what it's for. It's an identity for the row in the table, not a counter. – Tangentially Perpendicular Jan 05 '23 at 01:18
  • @TangentiallyPerpendicular I thought auto increment ID is for counter hehe because i always base on the last ID how many data inserted. – Arth Quilitis Jan 05 '23 at 01:29