我试图弄清楚如何从两个不同的select语句中获取绑定参数值并将其插入到新表中。
我的第一选择得到一个没有问题的阵列。我的第二个选择得到一个计数,以及除以该计数的数字180,但是使用where子句中第一个选择返回的值。
这一切都完美。
现在,基于第二个选择的执行,我想将每个选择的值插入一个新表中。
我要分别绑定每个选择的值,但是如何绑定两个选择的值以对它们执行插入?
$selectPLC = "
SELECT
sku_id, s.frm as frm, sg.code as code, s.matrl as matrl, s.color as color, cst
FROM plc;
";
try {
$PLCcheck = $MysqlConn->prepare($selectPLC);
$detailRslt = $PLCcheck->execute();
while ($PLCRow = $PLCcheck->fetch(PDO::FETCH_ASSOC)) {
print_r($PLCRow); //This prints the first array I need
$salesValues = [
":cst" => $PLCRow["cst"],
":frm" => $PLCRow["frm"],
":matrl" => $PLCRow["matrl"],
":color" => $PLCRow["color"]
];
$checkSales = "
SELECT
count(*) as salesCount,
180/count(*) as countDIV
FROM orders
WHERE cstnoc = :cst
AND frmc = :frm
AND covr1c = :matrl
AND colr1c = :color
AND date(substr(dateField1,1,4)||'-'||substr(dateField1,5,2)||'-'||substr(dateField1,7,2) ) between current_Date - 180 DAY AND current_Date
";
try{
$salesCheck = $DB2Conn->prepare($checkSales);
$salesResult = $salesCheck->execute($salesValues);
while ($salesRow = $salesCheck->fetch(PDO::FETCH_ASSOC)) {
print_r($salesRow); //This prints the 2nd array I need
$countValues = [
":salesCount" => $salesRow["salesCount"],
":countDiv" => $salesRow["countDiv"]
];
$insertSales = "
INSERT INTO metrics (cst, frm, matrl, color, salesCount, countDIV )
VALUES (
:cst, //from first array
:frm, //from first array
:matrl, //from first array
:color, //from first array
:salesCount, //from 2nd array
:countDiv //from 2nd array
)
";
$salesInsertPrep = $DB2Conn->prepare($insertSales);
$salesInsertExec = $salesInsertPrep->execute($countValues);
}
}catch(PDOException $ex) {
echo "QUERY TWO FAILED!: " .$ex->getMessage();
}
}
}catch(PDOException $ex) {
echo "QUERY ONE FAILED!: " .$ex->getMessage();
}
答案 0 :(得分:1)
获取第二个数组值而不是将它们添加到新数组中时,可以将它们添加到第一个值数组中,因此...... p
$countValues = [
":salesCount" => $salesRow["salesCount"],
":countDiv" => $salesRow["countDiv"]
];
使用
$salesValues[":salesCount"] = $salesRow["salesCount"];
$salesValues[":countDiv"] = $salesRow["countDiv"];
然后...
$salesInsertExec = $salesInsertPrep->execute($salesValues);
另一件事是,您可以在循环外准备一次插入,然后在循环中每次执行插入,因此看起来就像...
$insertSales = "
INSERT INTO metrics (cst, frm, matrl, color, salesCount, countDIV )
VALUES (
:cst, //from first array
:frm, //from first array
:matrl, //from first array
:color, //from first array
:salesCount, //from 2nd array
:countDiv //from 2nd array
)
";
$salesInsertPrep = $DB2Conn->prepare($insertSales);
while ($salesRow = $salesCheck->fetch(PDO::FETCH_ASSOC)) {
print_r($salesRow); //This prints the 2nd array I need
$salesValues[":salesCount"] = $salesRow["salesCount"];
$salesValues[":countDiv"] = $salesRow["countDiv"];
$salesInsertExec = $salesInsertPrep->execute($salesValues);
}