У меня есть две таблицы - таблица Контрахент и таблица заказов. Сначала я вставляю данные в таблицу Kontrahent
, затем в таблицу Orders
. При вставке в заказы в столбце IDAccount мне нужно вставить значение из столбца IDKontrahent из таблицы Kontrahent. Как?
try {
//Wstawianie nowego kontrahenta
$query = "INSERT INTO dbo.Kontrahent (Nazwa,Odbiorca,Dostawca,NIP,Regon,Uwagi,KodPocztowy,Miejscowosc,UlicaLokal,AdresWWW,Email,Utworzono,Zmodyfikowano,Telefon,Fax,OsobaKontaktowa,Pracownik,IDKraju,NrKonta,SWIFT,NazwaBanku,IDPaymentType,Archiwalny,IDRodzajuTransportu,SupplyCity,UlicaDostawy,KodPocztowyDostawy,NazwaAdresuDostawy,OsobaKontaktowaDostawy,TelefonDostawy,IDPlatnikaVat,CzyFirma,CzyGlownaFirma,NazwaKonta,LimitKredytu,IDPriceList) VALUES ('$complete_billing_name',1,0,'','','','$billing_postcode','$billing_state','$billing_address','','$billing_email','$isoDate','$ModDate',$billing_phone,'',NULL,0,616,'','','',NULL,0,NULL,'','','','','','',NULL,NULL,NULL,NULL,NULL,NULL)";
$result = $conn->prepare($query);
var_dump($result);
unset($query);
} catch (Exception $e) {
die(print_r($e->getMessage()));
}
Это не работает:
try{
$select = "SELECT IDENT_CURRENT(Kontrahent) ";
$result22 = $conn->query($select);
$result22 ->execute();
$query = "INSERT INTO dbo.Orders (IDOrderType, IDAccount, Number, IDOrderStatus, IDPaymentType, Remarks, IDUser, IDWarehouse, IDCurrency, IDCompany) VALUES (15,$result22,$customer_id,2,1,NULL,1,10,1,1)";
$result = $conn->query($query);
var_dump($result);
unset($result);
} catch (Exception $e) {
die(print_r($e->getMessage()));
}
РЕДАКТИРОВАТЬ:
Текущий код выглядит следующим образом:
// Inserting data into Order:
// IDOrder (broadcast automatically)
// Set OrderTypeID = 15 for orders from customers (14 orders from suppliers, 16 are offers)
// IDAccount - is the customer ID from the Contractor table
// Number - is the document number, e.g. order number from presta
// IDOrderStatus - is the current status of the order from the OrderStatus table (e.g. Open or you can add your own ..)
// IDPaymentType - this is the payment method for the order (from the PaymentTypes table)
// Remarks - Order notes
// IDUser - what user creates this entry, e.g. 1 = Admin (Users table)
// IDWarehouse - in which warehouse to create the order (ID from the Warehouse table)
// IDCurrency = 1 for PLN
// IDCompany = 1
// Get ID
$query = "SELECT IDENT_CURRENT('dbo.Kontrahent') AS ID";
$stmt = $conn->prepare($query);
if ($stmt->execute() === false) {
die("Error executing query.");
};
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$id = $result;
var_dump($result);
print_r($id);
$stmt = null;
// Insert into Orders
$query = "
INSERT INTO dbo.Orders
(IDOrderType,
IDAccount,
Number,
IDOrderStatus,
IDPaymentType,
Remarks,
IDUser,
IDWarehouse,
IDCurrency,
IDCompany)
VALUES
(15, ?, ?, 2, 1, NULL, 1, 10, 1, 1)
";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$stmt->bindValue(2, $customer_id, PDO::PARAM_INT);
if ($stmt->execute() === false) {
die("Error executing query.");
};
print_r($stmt);
$stmt = null;
// Get ID Order from Orders
$query = "SELECT TOP 1 IDOrder FROM dbo.Orders ORDER BY IDOrder DESC";
//$query ="SELECT IDENT_CURRENT('dbo.Orders') AS IDTowaru";
$stmt = $conn->prepare($query);
if ($stmt->execute() === false) {
die("Error executing query.");
};
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$idorder = $result;
var_dump ($idorder, $result);
$stmt = null;
Поиск IDTowaru от KodKreskowy. KodKreskowy является только одним идентичным в магазине и приложении.
$query = "SELECT IDTowaru FROM dbo.Towar WHERE KodKreskowy = '$product_sku' ";
$stmt = $conn->prepare($query);
if ($stmt->execute() === false) {
die("Error executing query.");
};
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$iditem = $result;
var_dump($iditem);
$stmt = null;
Вставка строк заказов с IDItem из таблицы Towar и IDOrder из таблицы Orders
// Inserting into OrderLines:
// IDOrderLine (broadcast automatically)
// IDOrder - Id of the order header from the Order table
// IDItem -ID of the item from the Item or Current Status table
// Quantity - Quantity of the item
// PriceNet - net price
// PriceGross - gross price including VAT
// IDVat - VAT rate ID from the VATRates table
// Remarks - any additional comments
// IDUser - what user creates this entry, e.g. 1 = Admin (Users table)
$query = "
INSERT INTO dbo.OrderLines
(IDItem,
IDOrder,
Quantity,
PriceNet,
PriceGross,
IDVat,
Remarks,
IDUser)
VALUES
(?, ?, ?, ?, ?, 1, 1, 1)
";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $iditem, PDO::PARAM_INT);
$stmt->bindParam(2, $idorder, PDO::PARAM_INT);
$stmt->bindValue(3, $quantity, PDO::PARAM_INT);
$stmt->bindValue(4, $product_price, PDO::PARAM_INT);
$stmt->bindValue(5, $product_price, PDO::PARAM_INT);
if ($stmt->execute() === false) {
die("Error executing query.");
};
$stmt = null;
} catch (Exception $e) {
die(print_r($e->getMessage()));
}
}
Это ошибка:
SQLSTATE[HY000]: General error: 20018 The INSERT statement conflicted with the FOREIGN KEY constraint "FK_OrderLines_Towar". The conflict occurred in database "greenmonkey", table "dbo.Towar", column 'IDTowaru'. [20018] (severity 16) [ INSERT INTO dbo.OrderLines (IDItem, IDOrder,Quantity, PriceNet, PriceGross, IDVat, Remarks, IDUser) VALUES (1, 1, 1, 42, 42, 1, 1, 1) ]1
Почему IDAccount и Number равны 1?
object(PDOStatement)#14917 (1) { ["queryString"]=> string(225) " INSERT INTO dbo.Orders (IDOrderType, IDAccount, Number, IDOrderStatus, IDPaymentType, Remarks, IDUser, IDWarehouse, IDCurrency, IDCompany) VALUES (15, ?, ?, 2, 1, NULL, 1, 10, 1, 1) " } array(1) { ["IDTowaru"]=> float(99) } array(1) { ["IDTowaru"]=> int(825) }
Далее, почему IDOrder и IDItem равны 1?
[ INSERT INTO dbo.OrderLines (IDItem, IDOrder,Quantity, PriceNet, PriceGross, IDVat, Remarks, IDUser) VALUES (1, 1, 1, 42, 42, 1, 1, 1) ]1