Right way to write multiple options search query - mysql

Belove is My search Query which works fine if I want any one of the passed value search , but what if i want exact match for particular value ?
I can use AND operator but that will increase number of lines ,for example how can i write query if I want particular location match ,pls can any one help me out with better search query
$sql = "SELECT * ";
$sql .= "FROM js_projects WHERE ";
$sql .= "jsp_title LIKE '%" . $valToSearch . "%' ";
$sql .= "OR jsp_nature LIKE '%" . $nature . "%' ";
$sql .= "OR jsp_etype LIKE '%" . $etype . "%' ";
$sql .= "OR jsp_location LIKE '%" . $location . "%' ";
$sql .= "OR jsp_date LIKE '%" . $jobdate . "%' ";
Edit
Suppose I have value for
valtosearch,location,jobdate,etype and I want exact match for all this values ,
or I can have any two of these values and I want exact match for them ,
or I can have any one of these values and I want exact match for that .
So how can I write query for all these possiblities?

Try like this. This will work fine
$condition=($location!=''?" AND jsp_location LIKE '%".$location."%":"");
$condition.=($jobdate!=''?" AND jsp_date LIKE '%".$jobDate."%":"");
$sql = "SELECT * FROM js_projects WHERE jsp_title LIKE '%".$valueToSearch."%' ".$condition;

Related

MySQL search multiple tables and in one table search multiple columns

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 3 model

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.

mysql_fetch_assoc() parameter 1 resource, object given in ... on line 6

Hi I've searched for a solution to this and found several answers and after many edits to the code and no success I'm asking here directly.
$return_arr = array();
$fetch = tep_db_query("select * from products, " . TABLE_PRODUCTS_DESCRIPTION . " WHERE products.products_status = '1' and products.products_id = " . TABLE_PRODUCTS_DESCRIPTION . ".products_id and " . TABLE_PRODUCTS_DESCRIPTION . ".language_id = '" . (int)$languages_id . "' and " . TABLE_PRODUCTS_DESCRIPTION . ".products_name LIKE '%" . $_GET['term'] . "%' LIMIT 0,10");
if($fetch === FALSE) {
die(mysql_error());
}
while ($row = mysql_fetch_assoc($fetch))
{
array_push($return_arr, $row['products_name']);
}
print json_encode($return_arr);
This returns: mysql_fetch_assoc() parameter 1 resource, object given in ... on line 6
I get where it is, just can't seem to find the problem.
Thanks in advance
Use tep_db_fetch_array()
$return_arr = array();
$fetch = tep_db_query("select * from products, " . TABLE_PRODUCTS_DESCRIPTION . " WHERE products.products_status = '1' and products.products_id = " . TABLE_PRODUCTS_DESCRIPTION . ".products_id and " . TABLE_PRODUCTS_DESCRIPTION . ".language_id = '" . (int)$languages_id . "' and " . TABLE_PRODUCTS_DESCRIPTION . ".products_name LIKE '%" . $_GET['term'] . "%' LIMIT 0,10");
echo $fetch; die;
if($fetch === FALSE) {
die(mysql_error());
}
while ($row = tep_db_fetch_array($fetch))
{
array_push($return_arr, $row['products_name']);
}
print json_encode($return_arr);
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
link- A link identifier returned by mysqli_connect() or mysqli_init()
escapestr- The string to be escaped.
You can find an example http://php.net/manual/en/mysqli.real-escape-string.php the first parameter needs to be the link identifier returned by mysqli_connect()

SQL Like Statement with multiple WHERE clauses

I am having an issue getting this to work. I have multiple WHERE statements that need to happen based on conditional information from the search query. Within there I can't seem to get the LIKE statements to work.
In the database the STREET_NUM & STREET_NAME are in different rows. I am using one input field to check against called $address
I am also struggling with getting the MIN & MAX to work.
Here is the Query:
$sql = "SELECT * FROM arc_property_res WHERE ( arc_property_res.STATUS = 'Active'";
if(!empty($_GET['city'])){
// City only query!
$sql .= "AND arc_property_res.CITY = '{$_GET['city']}'";
}
if(!empty($_GET['neighborhood'])){
// Hood only query!
$sql .= "AND arc_property_res.SUBDIVISION = '{$_GET['neighborhood']}'";
}
if(!empty($_GET['mls-number'])){
// MLS only query!
$sql .= "AND arc_property_res.MLS_ACCT = '{$_GET['mls-number']}'";
}
if(!empty($_GET['min-price']) && !empty($_GET['max-price'])){
// MIN AND MAX only query!
$sql .= "AND arc_property_res.LIST_PRICE = MIN('{$_GET['min-price']}') MAX('{$_GET['max-price']}')";
}
if(!empty($_GET['num-of-beds'])){
// BEDS only query!
$sql .= "AND arc_property_res.BEDROOMS = '{$_GET['num-of-beds']}'";
}
if(!empty($_GET['num-of-baths'])){
// BATHS only query!
$sql .= "AND arc_property_res.BATHS_FULL = '{$_GET['num-of-baths']}'";
}
if(!empty($_GET['mls-number'])){
// BATHS only query!
$sql .= "AND arc_property_res.MLS_ACCT = '{$_GET['mls-number']}'";
}
if(!empty($_GET['address'])){
$sql .= "AND arc_property_res.STREET_NUM LIKE '%{$_GET['address']}'";
$sql .= "OR arc_property_res.STREET_NAME LIKE '{$_GET['address']}%'";
}
$sql .= ") ORDER BY {$orderby}{$price_order}{$comma}{$list_date}";
I think all you need are some parentheses around the arc_property_res.STREET_NUM. Further, I would recommend you add some spaces around each line in your entire code so that you don't get syntax errors.
if(!empty($_GET['address'])){
$sql .= " AND (arc_property_res.STREET_NUM LIKE '%{$_GET['address']}' ";
$sql .= " OR arc_property_res.STREET_NAME LIKE '{$_GET['address']}%') ";
}
In addition to the obvious "Bobby Tables" issue that your query has, the problem at hand is that you do not insert a space in front of AND. This results in queries that look like this:
AND arc_property_res.BEDROOMS =3AND arc_property_res.BATHS_FULL =2
Note that there is no space between 3 and AND - a syntax error.
You should look into parametrizing your queries, and modifying it in a way that ignores the parameters that have been set to NULL.
SELECT * FROM arc_property_res WHERE ( arc_property_res.STATUS = 'Active'
AND (arc_property_res.CITY = #cityParam OR #cityParam is NULL)
AND (arc_property_res.SUBDIVISION = #subdiv OR #subdiv is NULL)
...
)
This modification would let you keep the query the same regardless of the number of parameters that were actually set, get you the same results, taking pretty much the same time.
$sql .= "AND arc_property_res.LIST_PRICE = MIN('{$_GET['min-price']}') MAX('{$_GET['max-price']}')";
The min and max functions are for when you want to get the min and max of a field in your database.
What you want is to compare the list price to see if it falls in between the min and max values supplied by the user.
$sql .= " AND arc_property_res.LIST_PRICE >= '{$_GET['min-price']}' AND arc_property_res.LIST_PRICE <= '{$_GET['max-price']}'";

Correcting an UPDATE statement (and making it more secure!)

I'm trying to a single value in my DB...When I run it through the console, it works correctly (as I'm replacing the variables with numbers and text).. However, My query is not returning a value for book ID when I insert the PHP variable for it.. It's because the book_id is unpopulated...
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query
The echoed query states:
UPDATE books SET readstatus='half' WHERE book_id=0
The book ID is stored in the URI as bookstatusupdate.php?book_id=
Just cannot figure this one out!
It would help to know the error. Firstly, echo out the query:
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query;
I would guess that $book_id is unpopulated, so the query fails. What you should really be doing to make it secure is casting integers with (int) and wrapping strings in mysqli_real_escape_string().
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
If you're trying to get data from the URL, do it like so:
$book_id = (int) $_GET['book_id'];
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
echo $query;