0

I have a basic web form that takes 3 inputs and inserts them into a database table. The DB set up:

    require_once 'MDB2.php';
    include "sql-connect.php";

    $host = 'host.yyy.uk';
    $dbName = 'user01';
    $dsn = "mysql://$username:$password@$host/$dbName"; 

    $db = &MDB2::connect($dsn); 
    if (PEAR::isError($db)) { 
        die($db->getMessage());
    }

    $db->setFetchMode(MDB2_FETCHMODE_ASSOC);

But even if the data is entered correctly into the DB and the data is inputted into the DB, php returns an error (Invalid query: Duplicate entry 'AAA123(ACode)' for key 'PRIMARY). This is my code for handling the form:

if (isset($_POST['submit'])) {
    $sql = "INSERT INTO MODULES (APart, ACode, ATitle) VALUES ('$_POST[APart]', '$_POST[ACode]', '$_POST[ATitle]')";

    mysql_query($sql);

    $endResult = mysql_query($sql);

    if (!$endResult) {
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $sql;
        die($message);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

You are running the query twice.

The first time, it succeeds but you do nothing with the result.

The second time, it fails - however, first succeeds, so you get some partial success (data is created).

Just remove the duplicate.

if (isset($_POST['submit'])) {
    $sql = "INSERT INTO MODULES (APart, ACode, ATitle) VALUES ('$_POST[APart]', '$_POST[ACode]', '$_POST[ATitle]')";

    // mysql_query($sql); /* REMOVE THIS LINE - this query succeeds */

    $endResult = mysql_query($sql); /* LEAVE THIS LINE - this fails if the first succeeds, because of your key constraints */

    if (!$endResult) {
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $sql;
        die($message);
    }
}

And also, look into PDO and MySQL libraries to prevent yourself from injection.

Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
0

Error:Duplicate entry means you are trying to insert a row which is already present in your Database.

Solution
Remove the primary key from the column (Acode) or add unique index on multiple columns instead of the primary key.

Indexes Best practices

Sumithran
  • 6,217
  • 4
  • 40
  • 54