create ordering for php table without doing two queries to the database
$q4 = "SELECT order_id FROM menu WHERE category_id = $cat_id";
$r4 = mysqli_query($dbc, $q4);
$num_items = mysqli_num_rows($r4)+1;
$q5 = "INSERT INTO menu (category_id, order_id, item, price, date_added, name) VALUES ('$cat_id', '$num_items', '$item', $开发者_JAVA技巧price, NOW(), $name)";
$r5 = mysqli_query($dbc, $q5);
As of right now im doing one initial query to get the total amount of rows in the table so I can add the right order_id to the newly inserted row.
Basically, I want to retain the 1,2,3,4 so I the user can edit the order themselves
Is there a way to do this in one query? Or perhaps you guys know a better method?
Thanks
A. using composite primary key on category_id, order_id
, and build an auto increment on that, like
create table menu
(
category_id int(10) unsigned default 0,
order_id int(10) unsigned auto_increment,
item int(10) unsigned default 0,
price double(10, 2) unsigned default 0,
date_added datetime,
name varchar(255),
primary key(category_id, order_id)
);
B: use a sub-query during insert, like
insert into menu
(category_id, item, price, date_added, name, order_id)
select
$category_id as category_id,
$item as item,
$price as price,
now() as date_added,
$name as name,
(select max(order_id) from menu where category_id=$category_id)+1 as order_id
from dual;
You should set AUTO_INCREMENT
on your order_id
. Then MySQL will automatically assign the next value to order_id
as long as you don't explicitly specify one.
If you haven't, you should also set order_id
to be unique.
精彩评论