[英]How to handle data received from unioned select statements
Hello I'm trying to create a search function for my website. 您好,我正在尝试为我的网站创建搜索功能。 I have this method that has the query 我有这种方法的查询
public function search_all($data)
{
$query = [];
$result = $this->db->query('
SELECT blog_title FROM blog WHERE blog_title LIKE "%'. $data . '%"
UNION
SELECT body FROM blog WHERE body LIKE "%'. $data . '%"
UNION
SELECT username FROM users WHERE username LIKE "%'. $data . '%"
');
while ($row = $result->fetch_assoc())
{
$query[] = $row;
}
$result->free();
return $query;
$mysqli->close();
}
Then I have the method that handles the user input 然后我有处理用户输入的方法
public function search()
{
if (isset($_POST['search']))
{
$search_term = trim($_POST['search_term']);
$terms = $this->search->search_all($search_term);
foreach ($terms as $term)
{
var_dump($term);
}
}
}
The search works sort of. 搜索的工作原理。 If I search a username or a blog title it then I can echo it back like this 如果我搜索用户名或博客标题,则可以像这样回显
echo $term['blog_title'];
if I var_dump then I get something like 如果我var_dump然后我得到类似
array (size=1)
'blog_title' => string 'BillyBob' (length=8)
My question is why does it always retrun blog_title as the key. 我的问题是为什么它总是重新运行blog_title作为键。 I thought I would have to do something like 我以为我必须做类似的事情
If I want to echo the blog title 如果我想回应博客标题
echo $term['blog_title'];
If I want to echo the username 如果我想回应用户名
echo $term['username'];
In the union of two tables either the fields of both tables should be same or the alias should be same for both the tables. 在两个表的并集中,两个表的字段应相同或别名应相同。
Please try this query. 请尝试此查询。
$result = $this->db->query('
SELECT body,blog_title,'' as username FROM blog WHERE blog_title LIKE "%'. $data . '%" OR body LIKE "%'. $data . '%" OR username LIKE "%'. $data . '%"
UNION
SELECT '' as body,'' as blog_title,username FROM users WHERE username LIKE "%'. $data . '%"
');
This query will select records when search will match with blog_title or body or username. 当搜索与blog_title或正文或用户名匹配时,此查询将选择记录。 And you will able to fetch all three fields' value for fetched records. 您将能够获取所有三个字段的记录值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.