Search code examples
phpmysqlinsert-id

PHP, mysql, primary key remains unchanged for two records


I've got following code, as seen, I have two INSERT statements, which insert two records - one with current date and the second one -1 day. The problem seems to be with a mysql_insert_id. I'm getting following error:

Duplicate entry '28' for key 'PRIMARY'

Looks like the ID remains the same for both statements and also the first "INSERT" is added without any trouble, the problem is at the line where trying to add the second record into the same table. Here's the script:

<?
include("session.php");
include("database_common.php");
if (isset($campaignName) & isset($campaignRedirect))    {
    $dataTable = 'qrData_'.$_SESSION['displayName'];
    $statTable = 'qrStat_'.$_SESSION['displayName'];
    $query = mysql_query("INSERT INTO ".$dataTable." VALUES(".mysql_insert_id($connection).", '".$campaignRedirect."', '".$campaignName."');", $connection);
    $statBlank1 = mysql_query("INSERT INTO ".$statTable." VALUES(".mysql_insert_id($connection).", CURDATE() - INTERVAL 1 DAY, 0, '".$campaignName."');", $connection);
    $statBlank2 = mysql_query("INSERT INTO ".$statTable." VALUES(".mysql_insert_id($connection).", CURDATE(), 0, '".$campaignName."');", $connection);
    if ($statBlank1) echo "stat 1 ok";
    else echo mysql_error($connection);
    if ($statBlank2) echo "stat 1 ok";
    else echo mysql_error($connection);
    if ($query) die("<center>Kampaň úspešne vytvorená<br><br><button      onclick='parent.jQuery.fancybox.close();' name='submit' class='btn btn-primary'>Zatvoriť</button></center>");
    else die("<center>Vyskytla sa chyba. Prosím, zopakujte Vašu požiadavku.</center>"); 
}
?>

Here's a table structure:

`id` int(11) NOT NULL AUTO_INCREMENT,  
`date` date DEFAULT NULL,  `usageCount` int(11) DEFAULT NULL,  
`campaign` varchar(45) DEFAULT NULL,  PRIMARY KEY (`id`)

any suggestions?


Solution

  • Okay guys, I made it a bit amish, but it works. I'm getting last id directly from mysql and increase it by 1 in a next record like this:

    $statBlank1 = mysql_query("INSERT INTO ".$statTable." VALUES(ID, CURDATE() - INTERVAL 1 DAY, 0, '".$campaignName."');");
    $statBlank2 = mysql_query("INSERT INTO ".$statTable." VALUES(LAST_INSERT_ID() + 1, CURDATE(), 0, '".$campaignName."');", $connection);
    

    ID in the first query is undefined, however table structure always changes NULL value to NOT NULL, which will be, in this case the next incremented value. Hope somebody will find this helpful.