首页 文章

将订单值从php购物车转移到MySQL

提问于
浏览
0

我正在尝试在登录用户获得积分/积分的网站内设置“结帐/订单”页面 . 一旦他们赚取了一定数量的这些积分,他们就可以去购物车并只用这些积分付款 . (没有钱换手,所以不涉及paypal /结账/运输/税收等) .

我已经完成了'shopping cart'页面和'view cart'页面(查看购物车代码在this page上),这要归功于Steve和KMK;) .

我的MySQL数据库上有两个表,'orders'(包含订单ID,用户ID,总计和时间戳)和'order_contents'(订单内容ID,订单ID,产品ID,数量和价格) . 'total'是总价,'price'是每个产品的价格 .

我试图通过 submit_cart.php 文件(下面的代码)将用户从视图购物车页面中选择的项目(即产品,数量等)放入数据库中的'order'和'order_contents'表中,但它无法正常工作 .

What does work on this code 是它将新行/ order_id放入orders表以及users_id .

What doesn't work: 订单的总价格在数据库上没有't get inserted (shows up as ' 0',它显示第一条错误消息(结尾为1) .

什么都没有插入'order_contents'表,此时我假设它是因为插入'orders'表不起作用或某种方式购物车会话变量不会跨越(?)但我很高兴得到纠正......

如果有人可以伸出援助之手,甚至建议采用不同的方法,请随意!谢谢!

<?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');
?>

2 回答

  • 2

    您已将总变量设置为0,这就是为什么订单表上的总成本显示为零的原因 .

    $total = 0; // Total cost of the order.
    
  • 0

    这是一个非常简单的示例,它使用您可能觉得有用的存储过程 .

    完整的脚本:http://pastie.org/1268992

    希望能帮助到你 :)

    Example stored procedure calls

    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;
    

    Example PHP script

    <?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
    ", $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
    ", $v["item_id"],$v["product_id"],$v["price"],$v["qty"],$v["subtotal"]); } echo sprintf("order total = %s
    ", $total); } catch(exception $ex){ //handle errros and rollback $conn->rollback(); echo sprintf("order error - %s
    ", $ex->getMessage()); } $conn->close(); ?>

    Example MySQL script

    -- 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);
    

相关问题