1

I'm creating a PHP script to insert rows into a database called orders based on a shopping cart that is stored in an associative array using a sessional array $_SESSION['cart']. The database looks something like this:

orders
----------+--------------+-------------+-------------+-------------+
   Id     |   Username   |   Item1Id   |   Item2Id   |   Item3Id   |
----------+--------------+-------------+-------------+-------------+
1         | a@aa.com     |   8000001   |   8000002   |   800003    |
----------+--------------+-------------+-------------+-------------+
5         | a@aa.com     |   7000001   |   6000002   |   700003    |
----------+--------------+-------------+-------------+-------------+
7         | b@bb.com     |   8000001   |   8000002   |    NULL     |
----------+--------------+-------------+-------------+-------------+
10        | a@aa.com     |   3000001   |   1000002   |   800009    |
----------+--------------+-------------+-------------+-------------+

Id column type is CHAR(20) as I may choose to use letters later on.

As part of inserting the row, I need to assign an Id (Primary Key) to the order row which will be set to 1 higher than the current highest Id number found.

The whole script works perfectly; query finds highest Id in the table and I increment that by 1 and assign it to a variable to use as part of the insert query. The only problem is that "SELECT MAX(Id) FROM orders" can't seem to find anything higher than 9. Is there a condition which prevents the SELECT MAX(Id) from identifying anything in double digits?

I've got it written like:

$highestID = mysqli_query($conn, "SELECT MAX(Id) FROM orders");

$orderID = $highestID +1;

I've emptied the database except for Id numbers1 and 2. Running the PHP script inserts new rows with Id numbers 3, 4, 5 except when it gets to 10, the script is unable to as it produces an error of having duplicate primary key of '10' (from $orderID's value). Even when manually entering a row into the database with Id of '25', $orderID still only returns '10' when I echo out its result.

I have not set any specific limits to the amount of rows that can be entered or anything like that.

4

2 回答 2

0

Id就是char(20)这样order by Id使用字符串排序。您可以使用castorconvert函数对数字进行排序。

喜欢: select max(cast(Id as unsigned)) from orders

于 2013-05-06T03:23:39.883 回答
-1

对于自动增量 PK,您真的不需要经历所有这些麻烦。这是你可以如何去做的。

第 1 步:在您的 phpmyadmin 中,编辑您的表格,然后A_I选中您的 PK 列的复选框。

第 2 步:从 PHP 插入时,将该字段留空。current max + 1它会自动为您的 PK分配一个值。

例如,

$query = "Insert into mytable (id, name) values ('', 'Name1'), ('', 'Name2')";

编辑:你真的不能有一个CHAR(20)PK,然后期望增量起作用。

于 2013-05-06T03:19:37.803 回答