php search query for multiple inputs into one field - php

I just want to input mobile_no1 and mobile_no2 and want to search in mobile_no.
I have a table with mobileno, cusname, etc,
I want to search mobile number by giving first and last digits of mobile number.
How?
$table_name ='search1_ts1';
if(isset($_POST['tablename']) && !empty($_POST['tablename'])){
$table_name =$_POST['tablename'];
}
$search_query='SELECT mobile_no, fname, cus_name '.
'FROM $table_name '.
"WHERE mobile_no LIKE 'mobile_no1%' ".
"AND mobile_no LIKE '%mobile_no2'";
$conditionsql="";
if(isset($_POST['mobile_no1'], $_POST['mobile_no2']) &&
!empty($_POST['mobile_no1'])) {
$conditionsql.=" mobile_no1 like '%" . $_POST['mobile_no1'] . "%'";
}
if(isset($_POST['mobile_no2']) && !empty($_POST['mobile_no2'])){
$conditionsql.=" and mobile_no2 like '%" . $_POST['mobile_no2'] . "%'";

You should use the LEFT() and RIGHT() functions.
I am not 100% sure what you're trying to match but this one will match first digit of mobile_no1 and last digit of mobile_no2 in the mobile_no field.
Try this:
$searcy_query = "SELECT mobile_no, fname, cus_name FROM $table_name
WHERE mobile_no LIKE CONVERT(CHAR(1),LEFT(mobile_no1,1))+'%'
AND mobile_no like '%'+CONVERT(CHAR(1),RIGHT(mobile_no2,1))";

If you are asking to get the results which will have start (input 1) and end (input 2) numbers of the given search
$table_name ='search1_ts1';
if(isset($_POST['tablename']) && !empty($_POST['tablename'])){
$table_name =$_POST['tablename'];
}
$search_query="SELECT mobile_no, fname, cus_name FROM $table_name";
$conditionsql="";
if(isset($_POST['mobile_no1']) && !empty($_POST['mobile_no1'])) {
$conditionsql.=" mobile_no1 like '%" . addslashes($_POST['mobile_no1']) . "'";
}
if(isset($_POST['mobile_no2']) && !empty($_POST['mobile_no2'])){
$conditionsql.=" and mobile_no2 like '" .addslashes( $_POST['mobile_no2'] ). "%'";
}
$search_query = $search_query+'where'+$conditionsql;

Related

How to write SQL 'LIKE' query using '%' where and 'OR' for search operation?

I am trying to use SQL LIKE for two different column. Is it possible to use this type of operation?
I have already tried like :
$sWhere .= " file_name like '%" . $search_item . "%' OR name like '%" . $search_item . "%' and ";
But above code is only working for single case . i want to perform search for both.
this is my code:
if (isset($search_item) && $search_item != '') {
$sWhere .= " file_name like '%" . $search_item . "%' and ";
}
I want to perform search operation using both the column name with one search field.
Response :
SELECT a.id, a.file_name, a.file_path,a.upload_type,a.upload_by, b.username,a.addedon
FROM tbl_asd as a
INNER JOIN user as b on b.id = a.upload_by
WHERE a.upload_type = 'asd' and a.addedon >= ( CURDATE() - INTERVAL 1000 DAY ) and (file_name like '%asd%' OR upload_by like '%asd%') ORDER BY id desc limit 0,10
With "No Rows" Found!
Guide me!
Thanks!
You need to enclose the OR part of your WHERE clause in parentheses, otherwise you will get more results than you expect (basically any row which has file_name like '%" . $search_item . "%'). Use this instead:
$sWhere .= " (file_name like '%" . $search_item . "%' OR name like '%" . $search_item . "%') and ";
Note that your query as is can leave you open to SQL injection. Ideally you should be preparing a query instead using code similar to this:
$query = "SELECT ... FROM ... WHERE";
$params = array();
$types = '';
if (isset($search_item) && $search_item != '') {
$query .= " file_name like ? OR name like ? AND ";
$types .= 'ss';
array_push($params, "'%$search_item%'", "'%$search_item%'");
}
// add other where clauses in a similar way
// ...
// make sure we have a trailing `WHERE` clause
$query .= '1 = 1';
$stmt = $link->prepare($link, $query) or die($link->error);
$stmt->bind_param($types, ...$params);
$stmt->execute() or die($stmt->error);
$sWhere .= " (file_name like '%" . $search_item . "%' OR name like '%" . $search_item . "%') and ";
You could use concat for build the proper like condition
$sWhere .= " file_name like concat('%', $search_item ,'%') OR name like concat('%', $search_item ,'%') ";
(removed the AND at the end of the string)
Anyway you should take a look at your db driver for prepared statmenent and binding param because the use of PHP in SQL could produce SqlInjection

multiple field search form displaying entire database [duplicate]

This question already has answers here:
Search Form with One or More (Multiple) Parameters
(2 answers)
Closed 7 years ago.
I am trying to create a database with multiple fields for searching but it is displaying the entire database if there is an empty field. i suspect it is because of the OR's in the query and i am not sure how to fix it.
<?php
if (isset($_POST['Submit']))
{
$con = mysqli_connect();
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$surname = $_POST['surname'];
$firstname = $_POST['firstname'];
$maiden = $_POST['maiden'];
$birth = $_POST['birth'];
$death = $_POST['death'];
$keyword = $_POST['keyword'];
$sql = "SELECT * FROM obits WHERE surname LIKE '%" . $surname . "%' OR firstname LIKE '%" . $firstname . "%' OR maiden LIKE '%" . $maiden . "%' OR birth LIKE '%" . $birth . "%' OR death LIKE '%" . $death . "%' OR obittext LIKE '%" . $keyword . "%'";
$result = mysqli_query($con, $sql);
further down i have this:
if (isset($result) && $result->num_rows > 0);
then follows the table etc. i think i have all the pertinent info here. any suggestions? please use english rather than programmer, i am quite new at this. thanks in advance!
Let's look at one of the conditions:
surname LIKE '%" . $surname . "%'
Assuming, $surname is Miller here, you select all rows that have a surname like %Miller%. The % signs are wildcards, which can basically stand for anything. This means you are selecting all rows where the surname contains Miller with any string before or after it, including empty ones.
Now, if Miller would be empty in this case, you are looking for %%, so an empty string with anything before or after it -- so really any possible string. As a result, every row will be selected.
Since this is true not only for the surname, but for any of the columns, leaving any of the criteria blank will result in all rows being selected.
Find more info on SQL Wildcards.
To skip empty values in your where clause, you can build it dynamically:
$condition = "WHERE";
if(!empty($surname)){
$condition .= "surname LIKE '$surname' OR";
}
if(!empty($firstname)){
$condition .= "firstname LIKE '$firstname' OR";
}
// ...
$sql = "SELECT * FROM obits " . $condition;
Note:
There will be a trailing OR in the condition that you will have to remove.
If all conditions are blank, this will also lead to an error.
But it should give you an inpiration! :-)
Side Note:
You should look into prepared statements. Passing POST variables directly into an SQL statement is highly dangerous.

Search form query with multiple values - PHP / MYSQL

I'm having a little trouble with a search form I've been creating the functionality for. I basically want a form (on whatever page) to go to this page then list the relevant rows from my database. My problem is that the form has both a text field and a select field (for name and categories) and I've been unable to create the functionality for having these two values search the database together.
So heres what I want to happen: When you only type in the name and not the category, it will display from just the name, vise versa for the category and no name; then when both together it only displays rows with both of them in.
Heres what I have so far:
// 2. Create variables to store values
if(!$_GET['search-category'] == "") {
$searchName = $_GET['search-name'];
}
if(!$_GET['search-category'] == "select-your-category") {
$searchCat = $_GET['search-category'];
}
// 2. Create the query for the stored value. Matching it against the name, summary and sub type of my item.
$mainSearch = "SELECT attraction.*, type.type_name, sub_type.sub_type_name ";
$mainSearch .= "FROM attraction ";
$mainSearch .= "INNER JOIN sub_type ON attraction.sub_type = sub_type.sub_type_id ";
$mainSearch .= "INNER JOIN type ON attraction.type = type.type_id ";
$mainSearch .= "WHERE attraction.name LIKE '%" . $searchName . "%' AND (sub_type.sub_type_name LIKE '%" . $searchCat . "%' )";
$mainSearch .= "ORDER BY sub_type_name ASC";
// 2. run query
$result2 = $con->query($mainSearch);
if (!$result2) {
die('Query error: ' . mysqli_error($result2));
}
I'd refactor the code to something like -
foreach( $_GET['filters'] as $fname => $fval ) {
if( !$fval ) continue;
$where[] = "$fname LIKE '%{$fval}%'";
}
You need to include only those inputs that are non-empty in the query. Also you will need to address security issues like escaping inputs etc.
What you can do is that declare a variable called $search_condition and based on whether $searchName or $searchCat is null or not assign value to $search_condition
For e.g.
if (isset($searchName ) || !is_empty($searchName ))
{
$search_condition = "WHERE attraction.name LIKE '%" . $searchName;
}
if (isset($searchCat ) || !is_empty($searchCat ))
{
$search_condition = "sub_type.sub_type_name LIKE '%" . $searchCat . "%'";
}
if ((isset($searchName ) || !is_empty($searchName )) && (isset($searchCat ) || !is_empty($searchCat )))
{
$search_condition = "WHERE attraction.name LIKE '%" . $searchName . "%' AND (sub_type.sub_type_name LIKE '%" . $searchCat . "%' )";
}
Hope this might help you
Thanks
This is a comment, but I want to take advantage of formatting options...
You know, you can rewrite that this way...
// 2. Create the query for the stored value. Matching it against the name, summary and sub type of my item.
$mainSearch = "
SELECT a.*
, t.type_name
, s.sub_type_name
FROM attraction a
JOIN sub_type s
ON a.sub_type = s.sub_type_id
JOIN type t
ON a.type = t.type_id
WHERE a.name LIKE '%$searchName%'
AND s.sub_type_name LIKE '%$searchCat%'
ORDER
BY s.sub_type_name ASC;
";
You can just check that the relevant values aren't empty:
// 2. Create the query for the stored value.
// Matching it against the name, summary and sub type of my item.
$mainSearch = "SELECT attraction.*, type.type_name, sub_type.sub_type_name ";
$mainSearch .= "FROM attraction ";
$mainSearch .= "INNER JOIN sub_type ON attraction.sub_type = sub_type.sub_type_id ";
$mainSearch .= "INNER JOIN type ON attraction.type = type.type_id ";
$mainSearch .= "WHERE ";
if ($searchName) {
$mainSearch .= "attraction.name LIKE '%" . $searchName . "%'";
if ($searchCat) {
$mainSearch .= " AND ";
}
}
if ($searchCat) {
$mainSearch .= "sub_type.sub_type_name LIKE '%" . $searchCat . "%'"
}
$mainSearch .= "ORDER BY sub_type_name ASC";
// Double check that at least one of the search criteria is filled:
if (!$searchName && !$searchCat) {
die("Must supply either name search or category search");
}

PHP MySQL Search Combined Columns

I had just finished my search functionality for a users system when I found out that it didn't search the way I wanted it to.
If I have a datebase table with 2 columns called 'fname' and 'lname'.
In one row, 'fname' has a value of 'Ashley' and 'lname' has a value of 'Staggs'.
I can search for either 'Ashley' or 'Staggs' and I will get the results correctly, but if I search for 'Ashley Staggs', no results are displayed.
How would I do this properly?
My SELECT query is as follows:
SELECT * FROM `users` WHERE fname LIKE '%" . protect($_GET['s']) . "%' OR lname LIKE '%" . protect($_GET['s']) . "%'
I knew something like this would happen, but this time I can't figure it out.
Thanks,
Ashley
'Ashley Staggs' is neither in fname, nor in lname, so your request doesn't return anything. You could try to concatenate your MySQL fields:
SELECT * FROM `users` WHERE fname LIKE '%" . $_GET['s'] . "%' OR lname LIKE '%" . $_GET['s'] . "%' OR CONCAT(fname, ' ', lname) LIKE '%" . $_GET['s'] . "%'
[EDIT] Even better:
SELECT * FROM `users`
WHERE REPLACE(CONCAT(fname, lname, fname), ' ', '')
LIKE '%" . str_replace(' ', '', protect($_GET['s'])) . "%'
SELECT fname_lname FROM ( SELECT CONCAT(fname, ' ', lname) fname_lname FROM users ) users
WHERE fname_lname LIKE '%" . $_GET['s'] . "%'
You might try something like this - it'll just split the search string by spaces and search for each word:
$search = explode(' ', $_GET['s']);
$query = 'SELECT * FROM `users` WHERE 0';
foreach ($search as $v)
{
$v = mysql_real_escape_string($v);
$query .= " OR (`fname` LIKE '%{$v}%' OR `lname` LIKE '%{$v}%')";
}
// echo $query;
Regarding sp00m answer, I have a slightly different approach, but built on the same concept.
$search = preg_replace ( "/\s\s+/" , " " , $_GET['s']);
And then use this query:
"SELECT * FROM `users` WHERE CONCAT(fname, ' ', lname) LIKE '%" . $search . "%' OR CONCAT(lname, ' ', fname) LIKE '%" . $search . "%'"
EDIT
Just had an idea you could use. Basically, you could create two additional fields in the table - fname_lname and lname_fname , use the regex I mentioned before to get rid of unnecessary spaces, use explode() to check the word count. If you have two words, then you can use these two new fields, giving you only two conditions in the query. When you have only one word, you still have two conditions in the query.
hey i want to sugest a stronger more strong search but it required MyISAM table
code for this is
$q="you search string";
$searchArray = explode(" ", $q);
$query="SELECT * FROM cmusers WHERE MATCH (`firstname`, `lastname`, `email`) AGAINST ('";
$i=0;
foreach ($searchArray as $word) {
$query .= "+".$word."* ";
}
$query .= "' IN BOOLEAN MODE)";
$result=mysql_query($query) or die("Error founded:".mysql_error()."there is problem existing we feels a very great sorry");
$finded=mysql_num_rows($result);
working of this can be seen at http://www.funnenjoy.com
I will just do
SELECT * FROM users WHERE CONCAT(firstname, ' ', lastname) LIKE '%{$search}%'

Php Syntax Help

I'm working on a search function, it was working fine four days ago, now it's returning this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND state = 'AZ '' at line 1
what is the proper syntax for this line?
if($search_state !== "") {
$query .="AND state = '" . $search_state . " ' " ;
the entire portion is:
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new WHERE dummy = '' ORDER BY state ASC ";
if($search_co !== "") {
$query .= "AND name LIKE '%" . $search_co ."%' ";
}
if($search_first !== "") {
$query .= "AND contact LIKE '%" .$search_first."%' ";
}
if($search_last !== "") {
$query .= "AND contact LIKE '%" .$search_last."%' ";
}
if($search_city !== "") {
$query .="AND city = ' " . $search_city . " ' ";
}
if($search_state !== "") {
$query .="AND state = '" . $search_state . " ' " ;
}
You can't put AND conjunctions for your WHERE clause after an ORDER BY. Your ORDER BY clause has to come after the entirety of the WHERE clause.
You need to put the AND statements after the where, and before the sort_by.
Move the sort_by to the end of the php (append to the query string), and it should work.
Try this:
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new WHERE dummy = '' ";
if($search_co !== "") {
$query .= "AND name LIKE '%".$search_co."%' ";
}
if($search_first !== "") {
$query .= "AND contact LIKE '%".$search_first."%' ";
}
if($search_last !== "") {
$query .= "AND contact LIKE '%".$search_last."%' ";
}
if($search_city !== "") {
$query .= "AND city = '".$search_city."' ";
}
if($search_state !== "") {
$query .= "AND state = '". $search_state."' " ;
}
$query.= "ORDER BY state ASC"
As was said by others, your order by statement has to come last. Also, you had spaces surrounding the city name in the city = portion of the query. While this is valid SQL syntax, it's only going to return results where the city name is surrounded by spaces. I'm guessing that's not what you wanted.
Also, you may want to add some more fields to your order by. Right now, it will order by state, but will records come back randomly by state. Maybe something like
$query.= "ORDER BY state, city, name, id"
Finally, just FYI, if you're not carefully sanitizing your search inputs, this approach is susceptible to SQL Injection.
Also, you seem to have spaces between the single and double quotes which will make the query like this: AND state = ' AZ ' which is probably not what you want. You can also avoid the additional quotes and concatenations in PHP by using this syntax:
$query .= " AND state = '$search_state' ";
Of course I have to mention that you should sanitize your inputs to protect against SQL injection.
The WHERE part comes before the AND's in your code, which is wrong. This is what you want
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new WHERE dummy = '' ";
if($search_co !== "") {
$query .= "AND name LIKE '%" . $search_co ."%' ";
}
...
$query .= " ORDER BY state ASC ";
Also, for completeness sake, you could make the code a bit easier to read:
$query .= "AND name LIKE '%$search_co%' ";
because your string is double quoted
I think this might work:
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new ";
$conditions = array();
if(!empty($search_co)) {
$conditions[] = "name LIKE '%" . $search_co ."%' ";
}
if(!empty($search_first)) {
$conditions[] = "contact LIKE '%" .$search_first."%' ";
}
if(!empty($search_last)) {
$conditions[] = "contact LIKE '%" .$search_last."%' ";
}
if(!empty($search_city)) {
$conditions[] = "city = '" . $search_city . "' ";
}
if(!empty($search_state)) {
$conditions[] = "state = '" . $search_state . "' " ;
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
}
$query .= " ORDER BY state ASC";
Edit: The original version used empty, it should have been !empty. It's fixed now.
Edit 2: This also assumes you've already sanitized the variables using mysql_real_escape_string or similar.
Note that ORDER BY has to be after the WHERE clauses.
implode takes an array and turns it into a string with the specified string between the elements. So, given:
$myArray = array('A', 'B', 'C');
you can do
$myString = implode(' and ', $myArray);
which would put "A and B and C" into $myString.

Categories