0

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.

  • `$conn->query($sql);` is the line that actually runs the query. How is this code being called? You may be calling it twice, or posting the form twice, or using a loop or something. – gen_Eric Dec 08 '14 at 18:34
  • Unexpected places to check if the code is called twice: Do you have rewrite rules which perform a redirection? Do you have any `` or `` or similar tags which mistakenly have empty `src=` attributes, causing them to request the same URL twice? – Michael Berkowski Dec 08 '14 at 18:37
  • Just incase: I think your query might be vulnerable to SQL injection attacks. [Take a look here](http://bobby-tables.com) – Barranka Dec 08 '14 at 18:46
  • I got rid of the $conn line, and it stopped inserting duplicates. The $recordid line though does not return the record ID. It comes back blank when using $recordid = mysql_insert_id(); – Allen Harris Dec 08 '14 at 19:14

1 Answers1

0

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

Benison Sam
  • 2,755
  • 7
  • 30
  • 40