MYSQL duplicates when using ->insert_id

307 Views Asked by At

I was happy when I got this to work but it submits the order twice unless I comment out the last two lines. Is there a better way to write it so that I don't get duplicates?

$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$conn->query($sql);
$recordid = $conn->insert_id;

I did this this way because I'm trying to use the record ID as the order ID. I echo this order ID back to the customer on the purchase receipt.

updated code:

$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$recordid = mysql_insert_id();

no duplicates, but does not return the record ID.

1

There are 1 best solutions below

0
Benison Sam On

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future.
Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more information.
Alternatives to this function include:
mysqli_insert_id()
PDO::lastInsertId()

Try the following:

$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$conn->query($sql);
$recordid = mysql_insert_id();

Note:
Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

Hopefully, this and this will help...