我的代码存在问题。它工作得很好,除了它不会将自己保存到数据库中。这是代码:
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
时,查看它是否全部存储在会话/数组中。它只是不会添加到数据库中。
答案 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'));