PHP中没有保存到数据库的变量

时间:2014-08-19 10:41:18

标签: php mysql phpmyadmin

我的代码存在问题。它工作得很好,除了它不会将自己保存到数据库中。这是代码:

function createOrder($user, $cart, $price, $method) {
    try {
        $username = "root";
        $password = "";
        $connection = new PDO('mysql:host=localhost;dbname=dreamlineslaapsystemen', $username, $password);
        $connection->beginTransaction();


        $productList=$_SESSION['products'];
        $orderList=$_SESSION['orders'];
        $orderItems=$_SESSION['orderitems'];

        $orderid = generateOrderid();
        $allOrders = array();
        for($i=0; $i<count($orderList); $i++) {
            array_push($allOrders, $orderList[$i]->getID());
        }
        while(in_array($orderid, $allOrders)) {
            $orderid = generateOrderid();
        }
        $today = date("Y-m-d H:i:s"); 
        $order = new Order($orderid, $user->getID(), $price, $today, $method);
        $newOrder = array(
            ':id' => $orderid,
            ':userid' => $user->getID(),
            ':date' => $today,
            ':method' => $method
        );

        $addOrder = $connection->prepare('INSERT INTO orders(id, userid, date) VALUES (:id, :userid, :date, :method');
        $addOrder->execute($newOrder);

        array_push($orderList, $order);

        foreach($cart->getCart() as $item => $amount) { 
            $itemid=null;
            for($i=0; $i<count($productList);$i++) {
                if($productList[$i]->getID()==$item) {
                    $orderitem = new Orderitem($orderid, $i, $amount);
                    array_push($orderItems, $orderitem);
                    $newOrderitem = array(
                        ':orderid' => $orderid,
                        ':productid' => $i,
                        ':amount' => $amount
                    );

                    $addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount');
                    $addOrderitem->execute($newOrderitem);  
                }
            }
        }
        $connection->commit();
        $_SESSION['orders']=$orderList;
        $_SESSION['orderitems']=$orderItems;
        return $orderid;
    } catch(PDOException $e) {
        $connection->rollback();
        print "Er is iets fout gegaan: " . $e->getMessage() . "<br>";
        return null;
    }
}

它确实为数组和会话添加了所有内容,当我执行var_dump时,查看它是否全部存储在会话/数组中。它只是不会添加到数据库中。

1 个答案:

答案 0 :(得分:1)

您有3列,但您正在插入4个值。我假设您的表中有方法列,而且插入语句缺少关闭括号。

$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount, method) VALUES (:orderid, :productid, :amount, :method'));


$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount'));