我想要做的是将域列表发送到我的 php 脚本 ($_POST['domains']
),然后从域相似的表中获取每个员工。
这是一个使用 for 循环执行多个查询的示例。这是标准的,但需要更长的时间:
$domains = explode(",", $_POST['domains']);
$returnObj = new stdClass();
$employees = [];
foreach($domains as $domain) {
$domainLike = "%".$domain;
$query = $conn_databank->prepare("SELECT employee_id FROM employee WHERE domain LIKE ?");
$query->bind_param('s', $domainLike);
$query->execute();
$result = $query->get_result();
while($row = $result->fetch_assoc()) {
array_push($employees, $row['employee_id']);
}
}
$returnObj->employees = $employees;
echo json_encode($returnObj);
现在,通过一组数据,我得到了大约 3900 个结果,这是正确的。
我正在尝试的另一种方法是使用 LIKE ? 创建动态准备好的语句。 OR LIKE ?
执行速度更快,但返回的结果数量较少(大约 950 个):
$queryString = "SELECT employee_id FROM employee";
$actualQuery = "SELECT employee_id FROM employee";
$bindVariables = [];
for($i = 0; $i < count($domains); $i++) {
$domainLike = "%".$domains[$i];
if($i == 0) {
$queryString .= " WHERE (domain LIKE ?";
$actualQuery .= " WHERE (domain LIKE '".$domainLike."'";
}
else {
$queryString .= " OR domain LIKE ?";
$actualQuery .= " OR domain LIKE '".$domainLike."'";
}
if($i == count($domains) - 1) {
$queryString .= ")";
$actualQuery .= ")";
}
array_push($bindVariables, $domainLike);
}
$variables = count(explode("?", $queryString)) - 1;
$bindings = [];
$bindString = "";
for($i = 0; $i < $variables; $i++)
$bindString .= "s";
array_push($bindings, $bindString);
foreach($bindVariables as $variable)
array_push($bindings, $variable);
echo $actualQuery;
$query = $conn_databank->prepare($queryString);
call_user_func_array(array($query, 'bind_param'), makeValuesReferenced($bindings));
$query->execute();
$result = $query->get_result();
$returnObj = new stdClass();
$employees = [];
while($row = $result->fetch_assoc()) {
$employee = new stdClass();
$employee->id = $row['employee_id'];
array_push($employees, $employee);
}
$returnObj->employees = $employees;
echo json_encode($returnObj);
忽略$actualQuery
变量,这只是为了看看它是否正确构建了查询。
最佳答案
你的问题有点含糊,没有例子。但是,很明显,一个域可以匹配多个 like
条件。例如:xxx@gmail.com
将匹配“mail.com”和“gmail.com”。
您没有足够的信息来判断这是否是一个问题。因此,一个想法是确保域完整。因此,使用“@gmail.com”而不是“gmail”并使用像 concat('%', $domain) 这样的电子邮件
。
这可能不起作用,因为您可能需要更大的灵 active (例如,匹配“gmail.co.uk”)。如果是这种情况,那么 OR
可能更正确,因为它不包含重复项。
关于php - 具有相同数据的两个单独的 SQL 语句返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40719872/