I have three tables in my database which are:
messages
topics
comments
Each of these tables has two fields called 'content' and 'title'. I want to be able to use 'Like' in my sql statement to look at 'messages.content', 'messages.title', 'topics.content', 'topics.title', 'comments.content' and 'comments.title' using a keyword.
So far, my query is able to find results from only one table:
mysql_query("SELECT * FROM messages
WHERE content LIKE '%" . $keyword . "%'
OR title LIKE '%" . $keyword ."%'");
I am also wondering, once I get the results from multiple tables, how can I tell what result is from what table?
Any help would be greatly appreciated!
$query = "(SELECT content, title, 'msg' as type FROM messages WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')
UNION
(SELECT content, title, 'topic' as type FROM topics WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')
UNION
(SELECT content, title, 'comment' as type FROM comments WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')";
mysql_query($query);
So, you are getting result from all of the three tables, and you can identify which row came from which table by looking at its type value.
What you are probably looking for is the UNION command:
SELECT id, 'messages' as 'table' FROM messages
WHERE content LIKE '%keyword%'
OR title LIKE '%keyword%'
UNION
SELECT id, 'topics' as 'table' FROM topics
WHERE content LIKE '%keyword%'
OR title LIKE '%keyword%'
UNION
SELECT id, 'comments' as 'table' FROM comments
WHERE content LIKE '%keyword%'
OR title LIKE '%keyword%'
Two search in other tables you use:
SELECT `categories`.`title`, `posts`.`title` WHERE `categories`.`title` LIKE {$a} OR `posts`.`title` LIKE {$a}
The CATEGORIES and POSTS are tables of your database.
Html Search form:
<div class="header_top_right">
<form action="search.php" method="GET" class="search_form">
<input type="text" placeholder="Text to Search.." name="search">
<input type="submit" class="btn btn-default" value="">
</form>
</div>
Search.php:
<?php
if (isset($_GET['search']) || !empty($_GET['search'])) {
$search = mysqli_real_escape_string($db->link, $fm->validation($_GET['search']));
}
else{
header("Location:404.php");
}
?>
<?php
$query = "SELECT * FROM news_post WHERE title LIKE '%$search%' OR body LIKE '%$search%' OR tags LIKE '%search%'";
$post = $db->select($query);
if ($post) {
while ($result = $post->fetch_assoc()) {
echo"Database data like, $result['title']";
}
}
else{
echo "result Not found";
}
include database.php in search.php
class Database{
public function select($query){
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows > 0){
return $result;
}
else {
return false;
}
}
}
$db = new Database();
Related
Currently I am working on a project in Laravel but I am stuck.I want to create a SQL statement like this:
SELECT * FROM SPITems WHERE publisher_id=? AND feed_id=? AND (title LIKE '%?%' OR description LIKE '%?%')
Now I have this code:
$query = SPItem::orderBy('title');
if(isset($_GET['publisherID']) && is_numeric($_GET['publisherID']))
{
$query = $query->where('publisher_id', $_GET['publisherID']);
}
if(isset($_GET['productFeedID']) && is_numeric($_GET['productFeedID']))
{
$query = $query->where('program_id', $_GET['feedID']);
}
if(isset($_GET['search']))
{
$query = $query->orWhere('title', 'like', '%' . $_GET['search'] . '%');
$query = $query->where('description', 'like', '%' . $_GET['search'] . '%');
}
But that generates:
SELECT * FROM SPITems WHERE (publisher_id=? AND feed_id=?) OR (title LIKE '%?%') AND description LIKE '%?%'
How can I get the correct "or" order?
Check out the Logical Grouping section in the docs:
https://laravel.com/docs/master/queries#logical-grouping
It explains how to group conditions in the WHERE clause.
It should be something like:
if(isset($_GET['search']))
{
$query->where(function($query){
$query->where('title', 'like', '%' . $_GET['search'] . '%')
->orWhere('description', 'like', '%' . $_GET['search'] . '%');
});
}
You can use whereRaw
SPItem::whereRaw(" publisher_id=? AND feed_id=? AND (title LIKE '%?%' OR description LIKE '%?%')", array(?,?,?,?))
I built a query for searching one value across multiple tables. It works great as is, but I want to search multiple fields in the "customers" table ("last_name" and "company_name" additionally).
$sql = "SELECT first_name as name FROM customers WHERE first_name LIKE '%" . $keyword . "%'
UNION
SELECT name as name FROM events WHERE name LIKE '%" . $keyword . "%'
UNION
SELECT product_name as name FROM products WHERE product_name LIKE '%" . $keyword . "%'";
Do I just add more separate lines for each additional field like so?
"SELECT first_name as name FROM customers WHERE first_name LIKE '%" . $keyword . "%'
UNION
SELECT last_name as name FROM customers WHERE last_name LIKE '%" . $keyword . "%'
UNION
SELECT company_name as name FROM customers WHERE company_name LIKE '%" . $keyword . "%'
It doesn't seem the most efficient, so wanted to check. Thanks!
There is an efficient solution. Since you collect only name, you collect them into three different variable. and using backend language, you merge these 3 array.
example for php,
$sql1 = "SELECT first_name as name FROM customers WHERE first_name LIKE '%" . $keyword . "%';
//getting first array result by this query
$sql2 = "SELECT name as name FROM events WHERE name LIKE '%" . $keyword . "%'";
//getting second array result by this query
$sql3 = "SELECT product_name as name FROM products WHERE product_name LIKE '%" . $keyword . "%'";
//getting third array result by this query
$result = array_merge($sql1, $sql2, $sql3)
This solution will be applicable, if you can manage data by your backend language.
Convert the MySQL query to Codeigniter Query
$query = "(SELECT content, title, 'msg' as type FROM messages WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')
UNION
(SELECT content, title, 'topic' as type FROM topics WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')
UNION
(SELECT content, title, 'comment' as type FROM comments WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')";
mysql_query($query);
I have tried to convert it in Codeigniter
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
->from('message')
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->like("msg", $keyword);
->from('topics')
$this->db->or_like('content',$keyword,'after');
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
->from('comment')
The top one is in MySQL and bottom which I try to convert is in Codeigniter I m trying to search the keyword from selected columns from three tables. How I can convert the MySQL to Codeigniter. I'm trying to search the keyword from selected columns from three tables.
How I can convert the MySQL to Codeigniter
Try this
$this->db->select('content, title, msg as type');
$this->db->from('message');
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
$query1 = $this->db->get_compiled_select();
$this->db->select('content, title, msg as type');
$this->db->from('topics');
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->like("msg", $keyword);
$query2 = $this->db->get_compiled_select();
$this->db->select('content, title, msg as type');
$this->db->from('comment');
$this->db->or_like('content',$keyword,'after');
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
$query3 = $this->db->get_compiled_select();
$result = $this->db->query($query1." UNION ".$query2." UNION ".$query3);
return $result->result();
Note:- If you intend to use this make sure that your both the table column are same sequence and name.
I was told to try and make a new post and explain better.
I have a upload function on my webpage. And i want to block certain titles from a database called filter. But it dont work.
The php side looks like this.
$DB->query("SELECT COUNT(*) FROM filter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
if($DB->record_count() != 0) {
$Err = '<b>you cant upload this!</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
$Properties['Title'] contains this in my test: The.White.Tiger.Test.Dawe.avi
The.White.Tiger. is blocked in the database filter. and if run this query in SQL
SELECT COUNT(*) FROM filter WHERE '". The.White.Tiger.Test.Dawe.avi ."' LIKE CONCAT('%', filter, '%')
I get count 1
So the php side SHOULD deny upload because it has 1 entry on it.. But it dosnt? Is something wrong with the code?
I have now tried these in php witch gave 500 Internal Server error
SELECT id FROM filter WHERE 'filter' LIKE CONCAT('%', '" . $Properties['Title'] . "', '%')
if($DB->record_count() != 0) {
$Err = '<b>You cant upload!</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
}
}
SELECT COUNT(*) as 'count' FROM filter WHERE 'filter' LIKE CONCAT('%', '" . $Properties['Title'] . "', '%')
if($DB->record_count() != 0) {
$Err = '<b>You cant upload!</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
}
}
SELECT COUNT(*) as count FROM filter WHERE 'filter' LIKE CONCAT('%', '" . $Properties['Title'] . "', '%')
if($DB->record_count() != 0) {
$Err = '<b>You cant upload!</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
}
}
All off the above gave 500 internal server error
As I can see from a query you want to find existsing records with title like user (or someone else) entered.
Here you have two errors:
Wrong WHERE clause. After WHERE comes name of a table field, not value
filter in CONCAT is what? What's it value?
Suppose title column name in your table filter is column_title.
And you are looking for already existing title The.White.Tiger.Test.Dawe.avi in a table filter.
The query should be like this:
SELECT COUNT(*) as count FROM filter WHERE 'column_title' LIKE CONCAT('%', 'The.White.Tiger.Test.Dawe.avi', '%')
After query you have to check value of count and compare it to 1. If it's equals or more than 1 - you already have this title. Else - title is not in the table and you can perform adding or something else.
UPDATE:
As I see your real table structure - you should replace column_title to filter:
SELECT COUNT(*) as count FROM filter WHERE 'filter' LIKE CONCAT('%', 'The.White.Tiger.Test.Dawe.avi', '%')
I have a form where I want a user to enter one or more words. These words should then match mutiple columns in a MySQL database.
I have started to build some code but I'm stuck.
<?php
$term = $_SESSION['session_searchstring']; //Let's say that session is John Doe
$searchterm = explode(' ',$term);
$searchFieldName = "name";
$searchCondition = "$searchFieldName LIKE '%" . implode("%' OR $searchFieldName LIKE '%", $searchterm) . "%'";
$sql = "SELECT * FROM students WHERE $searchCondition;";
echo $sql; //Echo to test what mysql_query would look like
?>
The above code will output:
SELECT * FROM students WHERE name LIKE '%John%' OR name LIKE '%Doe%';
The problem is that I want to search in multiple columns ($searchFieldName). I have for example
customer_firstname
customer_lastname
And I want to match my searchstring against the content of both columns.. How would I continue?
Perhaps
$term = $_SESSION['session_searchstring']; //Let's say that session is John Doe
$searchterm = explode(' ',$term);
$searchColumns = array("customer_firstname","customer_lastname");
for($i = 0; $i < count($searchColumns); $i++)
{
$searchFieldName = $searchColumns[$i];
$searchCondition .= "($searchFieldName LIKE '%" . implode("%' OR $searchFieldName LIKE '%", $searchterm) . "%')";
if($i+1 < count($searchColumns)) $searchCondition .= " OR ";
}
$sql = "SELECT * FROM students WHERE $searchCondition;";
echo $sql; //Echo to test what mysql_query would look like
Produces
SELECT * FROM students WHERE (customer_firstname LIKE '%John%' OR customer_firstname LIKE '%Doe%') OR (customer_lastname LIKE '%John%' OR customer_lastname LIKE '%Doe%');
If your table is of MyIsam type or you can convert it to MyIsam, use MySQL Fulltext Search. if not, anyway, you can build a long query like
SELECT * FROM students WHERE name LIKE '%John%' OR name LIKE '%Doe%' OR lastname LIKE "%John%" OR lastname LIKE "%Doe%"
or union your columns into one another just for search (but this both are not prefered).
Also a good approach is to use fulltext search engines like Sphinx.
In my case I needed all search phrases/terms to match at least one column, no search phrase/term could be a no-match.
I ended up tweaking the example from Kermit in the following way:
public function getRawWhereFilterForColumns($filter, $search_columns)
{
$search_terms = explode(' ', $filter);
$search_condition = "";
for ($i = 0; $i < count($search_terms); $i++) {
$term = $search_terms[$i];
for ($j = 0; $j < count($search_columns); $j++) {
if ($j == 0) $search_condition .= "(";
$search_field_name = $search_columns[$j];
$search_condition .= "$search_field_name LIKE '%" . $term . "%'";
if ($j + 1 < count($search_columns)) $search_condition .= " OR ";
if ($j + 1 == count($search_columns)) $search_condition .= ")";
}
if ($i + 1 < count($search_terms)) $search_condition .= " AND ";
}
return $search_condition;
}
I only needed the contents of the Where-clause since I'm using Laravel and could put that into the rawWhere-method.
usage:
$search_condition = $this->getRawWhereFilterForColumns
("John Doe", array("column1", "column2"));
which produces
(column1 LIKE '%John%' OR column2 LIKE '%John%')
AND (column1 LIKE '%Doe%' OR column2 LIKE '%Doe%')
And finally you use this $search_condition in whatever way suits you, for example:
$sql = "SELECT * FROM students WHERE $search_condition;";
Or in my Laravel-case:
$modelInstances = Model::whereRaw
($search_condition)->paginate(self::ITEMS_PER_PAGE);
Perhaps this is an improved solution for either David or anybody else visiting this thread, like me, even if it's almost two years after the original post.