【发布时间】:2016-12-02 15:52:22
【问题描述】:
我遇到了一个问题,我无法搜索我想要的确切数据。 我可以很好地搜索数据库并以我想要的格式返回所有值。但是,我想添加按公司名称搜索的功能,并将这些结果显示在同一个表中。公司名称不存储在数据库中,而是在从 API 提取的数组会话中。我们将每个公司的 ID 存储在数据库中,该 ID 设置为数组中的 Keys。
我想知道是否有任何方法可以从数组和数据库搜索中获取给定的结果。 我知道我可以在我的所有 SQL SELECT 语句周围使用 foreach 循环来做到这一点,但问题是如果数组中没有匹配项,它将不会运行任何搜索,从而使其余搜索非常有限,因为通过 IP 搜索地址是造成这种情况的主要原因之一。我认为可能的唯一方法是在 SQL 语句中添加一个 foreach 循环,但我不知道这是怎么可能的,我也无法在网上找到任何文档。请帮忙!
这是我的代码,它根据 AJAX 发送的搜索框的输入运行。
// Start sessions, Connected to DB set customer array
session_start();
$conn = connect();
$customers = $_SESSION['array'];
// if ajax posted search input
if($_POST){
$search = mysqli_real_escape_string($conn, $_POST['search']);
//set a second input for checking against customers array and format to give results
$input = $search
$input = strtolower($input);
$input = "'$input'";
$result = preg_grep($input, $customers);
$arrayk = array_keys($result);
//SELECT Search mysql Query
$matchingcompanies = "";
foreach($arrayk as $id)
{
$matchingcompanies .= "'" . $id . "' OR ";
}
$matchingcompanies = substr($matchingcompanies,0,strlen($matchingcompanies)-4);
$query1 = "SELECT * FROM IPV4_linked WHERE `companyId` = (" . $matchingcompanies . ") OR concat(ipv4Address, ipv4Subnet, hostName, owner, siteName) like '%" . $search . "%'";
$view4 = mysqli_query($conn, $query1);
//Table Title row
echo "<div><table name ='ipv4' class='tableparent'><td class='tabled'>IP Address</td><td class='table'>Subnet</td><td class='table'>PC Name</td><td class='table'>Owner</td><td class='table'>Customer</td><td class='table'>Customer Site</td></tr>";
//loops through search results and echo table
while ($row = mysqli_fetch_array($view4)){
$id = $row['companyId'];
$company = $customers[$id];
echo "<tr><td class='tabled'>". $row['ipv4Address']."</td><td class='table'>". $row['ipv4Subnet']."</td><td class='table'>".$row['hostName']."</td><td class='table'>". $row['owner']."</td><td class='table'>".$company."</td><td class='table'>".$row['siteName']."</td></tr>";
}
echo"</table></div>";
}
?>
【问题讨论】:
-
你的查询
$view4是错误的,山姆。 -
我知道查询是错误的,在我添加 %search% 之后的部分之前它运行良好。但我不知道如何将这两个搜索结合起来,这就是问题所在。我认为 foreach php 包含是可能的,但我不知道是否是,谢谢
-
您是否尝试过上述链接中给出的解决方案?
-
或者只是尝试学习一下,像这样的用户条件
where siteName LIKE '%$search%' OR owner LIKE '%$search%' OR hostName LIKE '%$search%'然后按照上面链接中给出的答案进行操作
标签: php arrays search mysqli foreach