那里的所有答案都涉及迭代两个或多个相同长度的数组,或者使用相同的键,但不是这里。我尝试了所有的想法都无济于事。
我在同一个POST表单中提交了两个多项选择 - 购买的产品和未购买的产品。它们包含相同的产品,但由于多选择很少会在数组中产生相同的项目(想想有多少组合。)第一个foreach
工作正常并从MySQL中获取所有选定的任何客户"买"项目。然而,第二个嵌套的foreach
没有迭代 - 它只是从" hasn&ttt带来的第一个值"阵列。
HTML部分:
Find customers who have bought:
<form method="post" action="">
<select name="bought[]" size="5" multiple="multiple">
<option value="RD"> Brown T Shirt </option>
<option value="RDX"> Red T Shirt </option>
<option value="HD"> White T Shirt </option>
<option value="CB"> Black T Shirt</option>
<option value="DA"> Green T Shirt </option>
</select>
But who haven't bought:
<select name="notbought[]" size="5" multiple="multiple">
<option value="RD"> Brown T Shirt </option>
<option value="RDX"> Red T Shirt </option>
<option value="HD"> White T Shirt </option>
<option value="CB"> Black T Shirt</option>
<option value="DA"> Green T Shirt </option>
</select>
<div class="buttons>
<button class="large" type="submit">Get the CSV!</button>
</div>
</form>
然后是PHP:
<?php
foreach($_POST['bought'] as $bought) {
foreach($_POST['notbought'] as $notbought){
$selectsubs = mysqli_query("SELECT First_Name, Last_Name, Email, Territory
FROM Customers
WHERE Customer_Type = 'Active'
AND Products_Bought LIKE '%$bought%'
AND Products_Bought NOT LIKE '%$notbought%'
");
while($row = mysqli_fetch_assoc($selectsubs)) {
$csvWriter->addRow();
$csvWriter->addCol($row['Email']);
$csvWriter->addCol($row['First_Name']);
$csvWriter->addCol($row['Last_Name']);
$csvWriter->addCol($row['Territory']);
}
}
}
$csvWriter->writeFile("customers.csv");
?>
答案 0 :(得分:1)
假设Products_Bought字段是以逗号分隔的产品列表,我很想在单个SQL中执行此操作,类似这样(未经测试): -
foreach($_POST['bought'] AS $key=>$value) $_POST['bought'][$key] = mysqli_real_escape_string($con, $_POST['bought'][$key]);
foreach($_POST['notbought'] AS $key=>$value) $_POST['notbought'][$key] = mysqli_real_escape_string($con, $_POST['notbought'][$key]);
$bought = 'FIND_IN_SET("'.implode('", REPLACE(Products_Bought, "-", ",")) AND FIND_IN_SET("', $_POST['bought']).'", REPLACE(Products_Bought, "-", ","))';
$notbought = '!FIND_IN_SET("'.implode('", REPLACE(Products_Bought, "-", ",")) AND !FIND_IN_SET("', $_POST['notbought']).'", REPLACE(Products_Bought, "-", ","))';
$selectsubs = mysqli_query("SELECT First_Name, Last_Name, Email, Territory
FROM Customers
WHERE Customer_Type = 'Active'
AND $bought
AND $notbought");
这应该构建一个类似于以下内容的SQL: -
SELECT First_Name, Last_Name, Email, Territory
FROM Customers
WHERE Customer_Type = 'Active'
AND FIND_IN_SET("RD", REPLACE(Products_Bought, '-', ','))
AND FIND_IN_SET("RDX", REPLACE(Products_Bought, '-', ','))
AND !FIND_IN_SET("HD", REPLACE(Products_Bought, '-', ','))
AND !FIND_IN_SET("CB", REPLACE(Products_Bought, '-', ','))
然而,将购买的商品拆分到另一个表中可能会更好,每个客户/商品只有一行,而不是使用分隔列表。