将订单值从php购物车传输到MySQL [英] Transferring order values from php shopping cart to MySQL
问题描述
我正在尝试在一个网站上设置结帐/订购"页面,已登录的用户在该页面中获得积分/积分.一旦他们获得一定数量的这些积分,他们就可以去购物车并仅用这些积分付款. (没有钱易手,因此不涉及贝宝/结帐/运费/税金等).
I am trying to setup a "checkout/order" page within a site in which logged in users earn points/credits. Once they earn a certain amount of these points they can then go to a shopping cart and pay with these points only. (No money changes hands, so no paypal/checkout/shipping/taxes etc are involved).
我已经完成了购物车"页面和查看购物车"页面(查看购物车代码位于
I have done a 'shopping cart' page and 'view cart' page (view cart code is on this page), which works fine thanks to Steve and KMK ;).
我在MySQL数据库上有两个表,订单"(具有订单ID,用户ID,总时间和时间戳)和"order_contents"(订单内容ID,订单ID,产品ID,数量和价格). 总计"是总价格,价格"是每种产品的价格.
I have two tables on my MySQL database, 'orders' (which has order id, users id, total & time stamp) and 'order_contents' (order contents id, order id, product id, quantity and price). 'total' is total price, 'price' is price per product.
我正在尝试通过 submit_cart.php 将用户从视图购物车页面中选择的商品(即产品,数量等)放入数据库的订单"和"order_contents"表中>文件(下面的代码),但无法正常工作.
I am trying to get the items that the user selects (ie products, quantity etc) from the view cart page into the 'order' and 'order_contents' tables in the database via the submit_cart.php file (code below) but it isn't working properly.
此代码的作用是,它将新行/order_id以及users_id放入了orders表.
What does work on this code is that it puts a new row/order_id into the orders table, as well as the users_id.
不起作用的地方:未插入订单的总价(在数据库中显示为"0"),并且显示了第一条错误消息(带有1的结束).
What doesn't work: The total price of the order doesn't get inserted (shows up as '0' on the database) and it displays the first error message (with the 1 on the end).
什么也没有插入到"order_contents"表中,在这一点上,我认为这是因为在"orders"表中的插入无法正常工作,或者某种程度上购物车会话变量没有通过(?),但是我很高兴得到纠正...
Nothing gets inserted into the 'order_contents' table either, at this point I am assuming it is because the insert into the 'orders' table isn't working or somehow the cart session variables are not going across(?) but I am happy to be corrected...
如果有人可以伸出援手,甚至提出其他建议,请放心!谢谢!
If someone could lend a hand or even suggest a different approach please feel free! Thanks!
<?php
$page_title = 'Order Confirmation';
include ('./includes/header.html');
if (!isset($_SESSION['users_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
$users = $_SESSION['users_id']; // Temporary.
$total = 0; // Total cost of the order.
require_once ('/MySQL/database.php'); // Connect to the database.
@mysqli_autocommit ($dbc, FALSE);
$query = "INSERT INTO orders (users_id, total) VALUES
($users, $total)";
$result = @mysql_query($query);
if (@mysql_affected_rows($dbc) == 1) {
// Need the order ID.
$oid = @mysql_insert_id($dbc);
// Insert the specific order contents into the database.
$query = "INSERT INTO order_contents (order_id, products_id, quantity, price)
VALUES (";foreach ($_SESSION['cart'] as $pid =>$value) {
$query .= "$oid, $pid, {$value['quantity']}, {$value['price']})";
}
$query = substr($query, 0, -2); // Chop off last two characters.
$result = @mysql_query($query);
// Report on the success.
if (@mysql_affected_rows($dbc) == count($_SESSION['cart'])) { // Whohoo!
// Commit the transaction.
@mysqli_commit($dbc);
@mysql_close($dbc);
// Clear the cart.
unset($_SESSION['cart']);
// Message to the customer.
echo '<p>Thank you for your order.
It has been submitted for processing.</p>';
// Send emails and do whatever else.
} else { // Rollback and report the problem.
@mysqli_rollback($dbc);
@mysql_close($dbc);
echo '<p>Your order could not be processed due to a system error.
You will be contacted in order to have the problem fixed.
We apologize for the inconvenience 1.</p>';
// Send the order information to the administrator.
}
}
else { // Rollback and report the problem.
@mysqli_rollback($dbc);
@mysql_close($dbc);
echo '<p>Your order could not be processed due to a system error.
You will be contacted in order to have the problem fixed.
We apologize for the inconvenience 2.</p>';
// Send the order information to the administrator.
}
?>
</div></div>
<?php
include ('./includes/footer.html');
?>
推荐答案
这是一个非常简单的示例,该示例使用了可能有用的存储过程.
Here's a really simple example that uses stored procedures which you might find useful.
完整脚本在这里: http://pastie.org/1268992
希望它会有所帮助:)
存储过程调用示例
start transaction;
call insert_order(1);
call insert_order_item(1,1,2);
call insert_order_item(1,2,4);
call insert_order_item(1,3,6);
commit;
PHP脚本示例
<?php
// dummy session data
$userID = 1;
$cart = array(
array("product_id" => 1, "qty" => 2, "item_id" => 0, "price" => 0, "subtotal" => 0),
array("product_id" => 2, "qty" => 4, "item_id" => 0, "price" => 0, "subtotal" => 0),
array("product_id" => 3, "qty" => 6, "item_id" => 0, "price" => 0, "subtotal" => 0));
$conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);
try{
$conn->autocommit(FALSE); // start transaction
// create the order
$sql = sprintf("call insert_order(%d)", $userID);
$result = $conn->query($sql);
$row = $result->fetch_array();
$result->close();
$orderID = $row["order_id"]; // new order_id returned by sproc
$conn->next_result();
// loop your cart and insert order items
foreach($cart as $k => $v){
$sql = sprintf("call insert_order_item(%d,%d,%d)", $orderID, $v["product_id"],$v["qty"]);
$result = $conn->query($sql);
$row = $result->fetch_array();
$result->close();
$cart[$k]["item_id"] = $row["item_id"]; // save data returned by sproc incase you need it ??
$cart[$k]["price"] = $row["price"];
$cart[$k]["subtotal"] = $row["subtotal"];
$conn->next_result();
}
$conn->commit(); //all OK so commit order/order items...
echo sprintf("your order no. is %s<br/>", $orderID);
$total = 0;
foreach($cart as $k => $v){
$total += $v["subtotal"];
echo sprintf("item_id=%s, product_id=%s, price=%s, qty=%s, subtotal=%s<br/>",
$v["item_id"],$v["product_id"],$v["price"],$v["qty"],$v["subtotal"]);
}
echo sprintf("order total = %s<br/>", $total);
}
catch(exception $ex){
//handle errros and rollback
$conn->rollback();
echo sprintf("order error - %s<br/>", $ex->getMessage());
}
$conn->close();
?>
示例MySQL脚本
-- TABLES
drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varbinary(32) unique not null
)
engine=innodb;
drop table if exists products;
create table products
(
product_id smallint unsigned not null auto_increment primary key,
name varchar(255) unique not null,
price decimal(10,2) not null default 0
)
engine=innodb;
drop table if exists orders;
create table orders
(
order_id int unsigned not null auto_increment primary key,
user_id int unsigned not null,
order_date datetime not null,
total decimal(10,2) not null default 0,
key (user_id)
)
engine=innodb;
drop table if exists order_items;
create table order_items
(
item_id int unsigned not null auto_increment primary key,
order_id int unsigned not null,
product_id smallint unsigned not null,
qty smallint unsigned not null default 0,
price decimal(10,2) not null default 0,
subtotal decimal(10,2) not null default 0,
key (order_id),
key (product_id)
)
engine=innodb;
-- STORED PROCEDURES
drop procedure if exists insert_order;
delimiter #
create procedure insert_order
(
in p_user_id int unsigned
)
proc_main:begin
declare v_order_id int unsigned default 0;
insert into orders (user_id, order_date, total) values (p_user_id, now(), 0);
set v_order_id = last_insert_id();
-- do more things with v_order_id ??
select v_order_id as order_id;
end proc_main #
delimiter ;
drop procedure if exists insert_order_item;
delimiter #
create procedure insert_order_item
(
in p_order_id int unsigned,
in p_product_id smallint unsigned,
in p_qty smallint unsigned
)
proc_main:begin
declare v_item_id int unsigned default 0;
declare v_price decimal(10,2) default 0;
declare v_subtotal decimal(10,2) default 0;
select price into v_price from products where product_id = p_product_id;
set v_subtotal = v_price * p_qty;
insert into order_items (order_id, product_id, qty, price, subtotal) values
(p_order_id, p_product_id, p_qty, v_price, v_subtotal);
set v_item_id = last_insert_id();
-- do more things with v_item_id ??
update orders set total = total + v_subtotal where order_id = p_order_id;
select p_order_id as order_id, v_item_id as item_id,
v_price as price, v_subtotal as subtotal;
end proc_main #
delimiter ;
-- TEST DATA
insert into users (username) values ('f00'),('bar'),('alpha'),('beta'),('gamma');
insert into products (name, price) values ('product 1', 9.99),('product 2',12.34),('product 3',32.50),('product 4',1.99);
这篇关于将订单值从php购物车传输到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!