MYSQL query with variables that may not be set - mysql

I have a PHP file which is taking in seven variables like so:
$name=$_REQUEST['membername'];
$email=$_REQUEST['email'];
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
$phone=$_REQUEST['phone'];
$county=$_REQUEST['county'];
$IP=$_REQUEST['IP'];
Some of these will not be set. What I want to do is construct a query which will search the members table such that if only $email and $dob are set it will only search by $email and $dob, ignoring the others. Or if only $phone, $name, and $gender are set, it will search those three columns only.
Is there an easier method than constructing a big block of if isset functions covering all possible permutations?

If you don't want to search on a field, pass NULL for the parameter and structure your WHERE clause something like...
WHERE
( (#parameter1 IS NULL) OR (column1 = #parameter1) )
AND
( (#parameter2 IS NULL) OR (column2 = #parameter2) )
I don't spend much time in MYSQL so the syntax is probably a bit off but you get the idea.

Presuming that you use parameters to push values into the query...
SELECT *
FROM MyTable
WHERE name = COALESCE(#p1, name)
OR email = COALESCE(#p2, email)
OR dob = COALESCE(#p3, dob)
...
...
If you construct a query string in PHP you can, instead, take another tack:
function AddWhere(&$where, $dbFieldName, $fieldValue)
{
if ($fieldValue <> "")
{
if (strlen($fieldName) > 0)
$fieldName .= " AND ";
$fieldname .= '(' + $dbFieldName + ' = \'' + $fieldValue + '\')'
}
}
Then, when you're retrived the variables, build a SQL statement thusly
$whereClause = ''
AddWhere($whereClause, 'name', $name)
AddWhere($whereClause, 'email', $email)
AddWhere($whereClause, 'dob', $dob)
...
IF (strlen($whereClause) > 0)
{
$sql = 'SELECT * FROM MyTable WHERE ' + $whereClause
... etc
}
(I'm not great at PHP, so the syntax may be somewhat screwed up).

Related

Writing mysql query with two variable conditions with prepare statement and bind param [duplicate]

I need to change this query to use a prepared statement. Is it possible?
The query:
$sql = "SELECT id, title, content, priority, date, delivery FROM tasks " . $op . " " . $title . " " . $content . " " . $priority . " " . $date . " " . $delivery . " ORDER BY " . $orderField . " " . $order . " " . $pagination . "";
Before the query, there's code to check the POST variables and change the content of variables in the query.
//For $op makes an INNER JOIN with or without IN clause depending on the content of a $_POST variable
$op = "INNER JOIN ... WHERE opID IN ('"$.opID."')";
//Or
$op = "INNER JOIN ... ";
//For $title (depends of $op):
$title = "WHERE title LIKE'%".$_POST["title"]."%'";
//Or
$title = "AND title LIKE'%".$_POST["title"]."%'";
//For $content:
$content = "AND content LIKE '%".$_POST["content"]."%'";
//For $priority just a switch:
$priority = "AND priority = DEPENDING_CASE";
//For $date and $delivery another switch
$d = date("Y-m-d", strtotime($_POST["date"]));
$date = "AND date >= '$d' 00:00:00 AND date <= '$d' 23:59:59";
//Or $date = "AND date >= '$d' 00:00:00";
//Or $date = "AND date <= '$d' 23:59:59";
//For $orderField
$orderField = $_POST["column"];
//For $order
$order= $_POST["order"];
//For $pagination
$pagination = "LIMIT ".$offset.",". $recordsPerPage;
How I could do this query using prepared statement?
The query could be more static but this means to make different prepared statements and execute it depending of $_POST checks.
It depends on many variables because this query show results in a table that contains search fields and column to order.
A full example of query would be like this (depending of $_POST checks):
SELECT id, title, content, priority, date, delivery FROM tasks INNER JOIN op ON task.op = op.opId WHERE op IN (4851,8965,78562) AND title LIKE '%PHT%' AND content LIKE '%%' AND priority = '2' ORDER BY date DESC LIMIT 0, 10
An excellent question. And thank you for moving to prepared statements. It seems that after all those years of struggle, the idea finally is starting to take over.
Disclaimer: there will be links to my own site because I am helping people with PHP for 20+ years and got an obsession with writing articles about most common issues.
Yes, it's perfectly possible. Check out my article, How to create a search filter for mysqli for the fully functional example.
For the WHERE part, all you need is to create two separate arrays - one containing query conditions with placeholders and one containing actual values for these placeholders, i.e:
WHERE clause
$conditions = [];
$parameters = [];
if (!empty($_POST["content"])) {
$conditions[] = 'content LIKE ?';
$parameters[] = '%'.$_POST['content ']."%";
}
and so on, for all search conditions.
Then you could implode all the conditions using AND string as a glue, and get a first-class WHERE clause:
if ($conditions)
{
$where .= " WHERE ".implode(" AND ", $conditions);
}
The routine is the same for all search conditions, but it will be a bit different for the IN() clause.
IN() clause
is a bit different as you will need more placeholders and more values to be added:
if (!empty($_POST["opID"])) {
$in = str_repeat('?,', count($array) - 1) . '?';
$conditions[] = "opID IN ($in)";
$parameters = array_merge($parameters, $_POST["opID"]);
}
this code will add as many ? placeholders to the IN() clause as many elements in the $_POST["opID"] and will add all those values to the $parameters array. The explanation can be found in the adjacent article in the same section on my site.
After you are done with WHERE clause, you can move to the rest of your query
ORDER BY clause
You cannot parameterize the order by clause, because field names and SQL keywords cannot be represented by a placeholder. And to tackle with this problem I beg you to use a whitelisting function I wrote for this exact purpose. With it you can make your ORDER BY clause 100% safe but perfectly flexible. All you need is to predefine an array with field names allowed in the order by clause:
$sortColumns = ["title","content","priority"]; // add your own
and then get safe values using this handy function:
$orderField = white_list($_POST["column"], $sortColumns, "Invalid column name");
$order = white_list($_POST["order"], ["ASC","DESC"], "Invalid ORDER BY direction");
this is a smart function, that covers three different scenarios
in case no values were provided (i.e. $_POST["column"] is empty) the first value from the white list will be used, so it serves as a default value
in case a correct value provided, it will be used in the query
in case an incorrect value is provided, then an error will be thrown.
LIMIT clause
LIMIT values are perfectly parameterized so you can just add them to the $parameters array:
$limit = "LIMIT ?, ?";
$parameters[] = $offset;
$parameters[] = $recordsPerPage;
The final assembly
In the end, your query will be something like this
$sql = "SELECT id, title, content, priority, date, delivery
FROM tasks INNER JOIN ... $where ORDER BY `$orderField` $order $limit";
And it can be executed using the following code
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(str_repeat("s", count($parameters)), ...$parameters);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
where $data is a conventional array contains all the rows returned by the query.

MySQL optional filters for search query

I am working on a query that has an optional filter, so lets assume the table name is products and the filter is the id (primary key)
If the filter is not present I would do something like this:
SELECT * FROM products;
If the filter is present I would need to do something like this:
SELECT * FROM products WHERE id = ?;
I have found some potential solutions that can mix the 2 in sql rather than doing conditions in the back-end code itself
SELECT * FROM products WHERE id = IF(? = '', id, ?);
OR
SELECT * FROM products WHERE IF(? = '',1, id = ?);
I was just wondering which one would be faster (In the case of multiple filters or a very big table) Or is there a better solution to handle this kind of situation?
A better approach is to construct the WHERE clause from the parameters available. This allows the Optimizer to do a much better job.
$wheres = array();
// Add on each filter that the user specified:
if (! empty($col)) { $s = $db->db_res->real_escape_string($col);
$wheres[] = "collection = '$s'"; }
if (! empty($theme)) { $s = $db->db_res->real_escape_string($theme);
$wheres[] = "theme = '$s'"; }
if (! empty($city)) { $s = $db->db_res->real_escape_string($city);
$wheres[] = "city = '$s'"; }
if (! empty($tripday)) { $s = $db->db_res->real_escape_string($tripday);
$wheres[] = "tripday = '$s'"; }
// Prefix with WHERE (unless nothing specified):
$where = empty($wheres) ? '' :
'WHERE ' . implode(' AND ', $wheres);
// Use the WHERE clause in the query:
$sql = "SELECT ...
$where
...";
Simplest approach is OR:
SELECT *
FROM products
WHERE (? IS NULL OR id = ?);
Please note that as you will add more and more conditions with AND, generated plan will be at least poor. There is no fit-them-all solution. If possible you should build your query using conditional logic.
More info: The “Kitchen Sink” Procedure (SQL Server - but idea is the same)

SQL search multiple values in same field

I'm building a simple search algorithm and I want to break my string with spaces, and search my database on it, like so:
$search = "Sony TV with FullHD support";
$search = explode( ' ', $search );
SELECT name FROM Products WHERE name LIKE %$search[1]% AND name LIKE %$search[2]% LIMIT 6
Is this possible?
Yes, you can use SQL IN operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE you will need to use OR instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.
Try this
Using UNION
$sql = '';
$count = 0;
foreach($search as $text)
{
if($count > 0)
$sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
else
$sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";
$count++;
}
Using WHERE IN
$comma_separated = "('" . implode("','", $search) . "')"; // ('1','2','3')
$sql = "Select name From myTable WHERE name IN ".$comma_separated ;
This will works perfectly in both cases, one or multiple fields searching multiple words.
Hope this will help someone. Thanks
declare #searchTrm varchar(MAX)='one two three four';
--select value from STRING_SPLIT(#searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(#searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
This has been partially answered here:
MySQL Like multiple values
I advise against
$search = explode( ' ', $search );
and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;
$search = str_replace('"', "''", search );
But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.
function makeSQL_search_pattern($search) {
search_pattern = false;
//escape the special regex chars
$search = str_replace('"', "''", $search);
$search = str_replace('^', "\\^", $search);
$search = str_replace('$', "\\$", $search);
$search = str_replace('.', "\\.", $search);
$search = str_replace('[', "\\[", $search);
$search = str_replace(']', "\\]", $search);
$search = str_replace('|', "\\|", $search);
$search = str_replace('*', "\\*", $search);
$search = str_replace('+', "\\+", $search);
$search = str_replace('{', "\\{", $search);
$search = str_replace('}', "\\}", $search);
$search = explode(" ", $search);
for ($i = 0; $i < count($search); $i++) {
if ($i > 0 && $i < count($search) ) {
$search_pattern .= "|";
}
$search_pattern .= $search[$i];
}
return search_pattern;
}
$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();
I have not tested this code, but this is what I would do in your case.
I hope this helps.
You can try and execute below query:
SELECT name FROM Products WHERE REGEXP '.*Value1|.*Value2';
Pls note that there should not be a space before or after the pipe symbol
(|).
I know this is long time ago, but I have a solution. It can solved like this:
#intial query
query = 'SELECT var1, var2 FROM dbo.db_name WHERE'
if status :
query = query + " AND status='" + status + "'"
if type :
query = query + " AND Type='" + type + "'"
if number :
query = query + " AND Number='" + number + "'"
if cancel_request:
query = query + " AND CancelRequest='" + cancel_request + "'"
query = query + ' ORDER BY transid DESC'
cur.execute(query)

Search a whole table in mySQL for a string

I'm trying to search a whole table in mySQL for a string.
I want to search all fields and all entrees of a table, returning each full entry that contains the specified text.
I can't figure out how to search multiple fields easily; here are the details:
The table is "clients". It has about 30 fields and 800 entries, too much to show all at once in a browser. I would like to search for a name (i.e. "Mary"), but it could be in the shipping_name field or the billing_name field, or the email field, etc.
I would like to search all fields for any entries that contain the string "Mary". This is what I think should work but doesn't:
SELECT * FROM `clients` IN 'Mary'
Try something like this:
SELECT * FROM clients WHERE CONCAT(field1, '', field2, '', fieldn) LIKE "%Mary%"
You may want to see SQL docs for additional information on string operators and regular expressions.
Edit: There may be some issues with NULL fields, so just in case you may want to use IFNULL(field_i, '') instead of just field_i
Case sensitivity: You can use case insensitive collation or something like this:
... WHERE LOWER(CONCAT(...)) LIKE LOWER("%Mary%")
Just search all field: I believe there is no way to make an SQL-query that will search through all field without explicitly declaring field to search in. The reason is there is a theory of relational databases and strict rules for manipulating relational data (something like relational algebra or codd algebra; these are what SQL is from), and theory doesn't allow things such as "just search all fields". Of course actual behaviour depends on vendor's concrete realisation. But in common case it is not possible. To make sure, check SELECT operator syntax (WHERE section, to be precise).
Identify all the fields that could be related to your search and then use a query like:
SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
OR field2 LIKE '%Mary%'
OR field3 LIKE '%Mary%'
OR field4 LIKE '%Mary%'
....
(do that for each field you want to check)
Using LIKE '%Mary%' instead of = 'Mary' will look for the fields that contains someCaracters + 'Mary' + someCaracters.
In addition to pattern matching with 'like' keyword. You can also perform search
by using fulltext feature as below;
SELECT * FROM clients WHERE MATCH (shipping_name, billing_name, email) AGAINST ('mary')
If you are just looking for some text and don't need a result set for programming purposes, you could install HeidiSQL for free (I'm using v9.2.0.4947).
Right click any database or table and select "Find text on server".
All the matches are shown in a separate tab for each table - very nice.
Frighteningly useful and saved me hours. Forget messing about with lengthy queries!!
A PHP Based Solution for search entire table ! Search string is $string . This is generic and will work with all the tables with any number of fields
$sql="SELECT * from client_wireless";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' OR ";
}
// start the search in all the fields and when a match is found, go on printing it .
$sql="SELECT * from client_wireless ".$logicStr;
//echo $sql;
$query=mysql_query($sql);
Try this code,
SELECT
*
FROM
`customers`
WHERE
(
CONVERT
(`customer_code` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`customer_name` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`email_id` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`address1` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`report_sorting` USING utf8mb4) LIKE '%Mary%'
)
This is help to solve your problem mysql version 5.7.21
If you're using Sublime, you can easily generate hundreds or thousands of lines using Text Pastry in conjunction with multiple line selection and Emmet.
So in my case I set the document type to html, then typed div*249, hit tab and Emmet creates 249 empty divs. Then using multiple selection I typed col_id_ in each one and triggered Text Pastry to insert an incremental id number. Then with multiple selection again you can delete the div markup and replace it with the MySQL syntax.
for specific requirement the following will work for search:
select * from table_name where (column_name1='%var1%' or column_name2='var2' or column_name='%var3%') and column_name='var';
if you want to query for searching data from the database this will work perfectly.
One can take an export of the table in an excel sheet & find the string in the excel file itself.
This is not the best method and should be used with care as it can crash db with large amounts of tables and data. Somethings may need to be modified to use with your specific setup however should get you close.
<?php
class DBSearch{
// DB Connection
protected $db;
// Name of the DB to search in
protected $db_name = 'my_db_name';
// Tables to exclude from search
protected $excluded_tables = array(
'TABLE_I_DONT_WANT_INCLUDED',
);
// Search String
protected $search_string = '';
// Table has column
protected $has_column = '';
// Set the result limit per query
protected $limit = 5;
public function __construct($db_conn) {
parent::__construct();
$this->db = $db_conn;
}
public function search(string $search_str, string $has_column, array $exclude_table){
$this->search_string = $search_str;
$this->has_column = $has_column;
$this->excluded_tables = $exclude_table;
if(!empty($this->has_column)){
$table_names = $this->get_table_with_column($this->has_column,$this->excluded_tables);
}else{
$table_names = $this->get_all_tables($this->excluded_tables);
}
$query_string = $this->generate_query_string($table_names, $this->search_string);
$results = array();
foreach($query_string as $k=>$v){
$query = $v.' LIMIT '.$this->limit;
$results[] = $this->db->query($query)->result();
}
return $results;
}
/**
* Returns the column names associated with the table
* provided by the $table param
*
* #param string $table
* #return array
*/
private function get_table_column_names($table){
$response = array();
$sql = 'SELECT COLUMN_NAME, TABLE_NAME
FROM information_schema.columns
WHERE table_schema = ?
AND table_name = ?
ORDER BY table_name, ordinal_position';
$param = array($this->db_name, $table);
$result = $this->db->query($sql, $param);
if($result->num_rows() >= 1){
foreach ($result->result() as $v){
$response[$table][] = $v->COLUMN_NAME;
}
}
return $response;
}
/**
* Returns a object contaning the table names that
* have columns that have the name provided in $column
*
* You can also pass in a string or an array of tables not to in clude in
* the result set using the $exclude_table param
*
* #param string $column
* #param array|string $exclude_table
* #return object|boolean
*/
private function get_table_with_column($column, $exclude_table=NULL){
$sql = 'SELECT table_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (COLUMN_NAME = ?
OR COLUMN_NAME LIKE ?)
AND table_schema = ? ';
if(NULL !== $exclude_table){
if(is_array($exclude_table)){
foreach($exclude_table as $v){
$sql .= ' AND TABLE_NAME != "'.strip_quotes($v).'"';
}
}
if(is_string($exclude_table)){
$sql .= ' AND TABLE_NAME != "'.strip_quotes($exclude_table).'"';
}
}
$sql .= ' GROUP BY TABLE_NAME ORDER BY TABLE_NAME ';
$query_param = array($column, '%'.$column.'%', $this->db_name);
$result = $this->db->query($sql, $query_param);
if($result->num_rows() >= 1){
return $result->result();
}
return false;
}
/**
* Returns an object contaning the table names.
*
* You can also pass in a string or an array of tables not to in clude in
* the result set using the $exclude_table param
*
* #param array|string $exclude_table
* #return object|boolean
*/
private function get_all_tables($exclude_table=NULL){
$sql = 'SELECT table_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = ? ';
if(NULL !== $exclude_table){
if(is_array($exclude_table)){
foreach($exclude_table as $v){
$sql .= ' AND TABLE_NAME != "'.strip_quotes($v).'"';
}
}
if(is_string($exclude_table)){
$sql .= ' AND TABLE_NAME != "'.strip_quotes($exclude_table).'"';
}
}
$sql .= ' ORDER BY TABLE_NAME';
$query_param = array($this->db_name);
$result = $this->db->query($sql, $query_param);
if($result->num_rows() >= 1){
return $result->result();
}
return false;
}
/**
* Generates a search string for each table
* provided $table_names array
*
* #param array $table_names
* #param string $search_string
* #return array[]
*/
private function generate_query_string($table_names, $search_string){
$search_split = explode(' ', $search_string);
$search_a = isset($search_split[0]) ? $search_split[0]:'';
$search_b = isset($search_split[1]) ? $search_split[1]:'';
$queries = array();
if(is_array($table_names)){
foreach ($table_names as $v){
$query_string = 'SELECT * FROM '.$v->TABLE_NAME.' WHERE (';
foreach ($this->get_table_column_names($v->TABLE_NAME)[$v->TABLE_NAME] as $c){
$query_string .= '`'.$c.'` LIKE "%'.$search_string.'%" OR';
if(!empty($search_a)){
$query_string .= '`'.$c.'` LIKE "%'.$search_a.'%" OR';
}
if(!empty($search_b)){
$query_string .= '`'.$c.'` LIKE "%'.$search_b.'%" OR';
}
}
// Remoe Last OR
$query_string = substr($query_string, 0, strlen($query_string)-3). ')';
$queries[$v->TABLE_NAME] = $query_string;
}
}
return $queries;
}
}
// USEAGE
$search = new DBSearch($db_conn);
$exclude_table = array(
'tables',
'i_dont',
'want_searched'
);
$search->search('Something to search for', 'has_this_column', $exclude_table);
This essentials is a query builder for database tables and then runs the query on each table/column found in the DB. Maybe it will be helpful. Enjoy!

mysql and or query run together

I need to make a search engine where a user can search by name,course,member,year(text field) from the table fsb_profile fields are profile_name,profile_course,profile_member,profile_year
search will be with any one field
or
search will be with all the field
or
search will be with more than one field
-How it is possible by using only one query??
i am making the code like:-
$query="select * from fsb_profile
where profile_name = '".$_REQUEST['name']."'
and profile_member= '".$_REQUEST['type']."'
and profile_year= '".$_REQUEST['year']."'
and profile_course='".$_REQUEST['course']."'
or profile_name = '".$_REQUEST['name']."'
or profile_member= '".$_REQUEST['type']."'
or profile_year= '".$_REQUEST['year']."'
or profile_course='".$_REQUEST['course']."'";
-but it is not working?
try this query. using this query you can extract details using the combination of search factors
$query="select * from fsb_profile
where profile_name = '".$_REQUEST['name']."'
or profile_member= '".$_REQUEST['type']."'
or profile_year= '".$_REQUEST['year']."'
or profile_course='".$_REQUEST['course']."'";
If I understand you correctly, you want to search so that either all the fields match or that at least two fields match?
In that case I'd try the following:
$query="select * from fsb_profile
where
(
profile_name = '".$_REQUEST['name']."'
and profile_member= '".$_REQUEST['type']."'
and profile_year= '".$_REQUEST['year']."'
and profile_course='".$_REQUEST['course']."'
)
OR
(
(
profile_name = '".$_REQUEST['name']."'
AND
(
profile_member= '".$_REQUEST['type']."' OR
profile_year= '".$_REQUEST['year']."' OR
profile_course='".$_REQUEST['course']."'"
)
)
OR
(
profile_member= '".$_REQUEST['type']."'
AND
(
profile_year= '".$_REQUEST['year']."' OR
profile_course='".$_REQUEST['course']."'"
)
)
OR
(
profile_year= '".$_REQUEST['year']."' AND
profile_course='".$_REQUEST['course']."'"
)
)
This returns all sets where either all criteria match or a combination of at least two other criteria matches. I didn't try this really, but that's what I'd start off with.
First off, I would advise you to sanitize your input data. You should NEVER put user-entered data into an SQL query without checking it; that's just asking for trouble.
As for your question, it seems like you're having some trouble with the logic (ANDs and ORs) in your statement. With the statement you are using, you will get all records that match all four fields entered in the search engine, as well as all records that match ANY of the four fields entered. It might be best for you to just construct the query string on the fly, something like:
$arr = sanitize_data($_REQUEST);
$query = "select * from fsb_profile ";
$count = 0;
if ( isset($arr['name']) ) {
$query .= (($count > 0)?"and":"where")." profile_name = '".$arr['name']."' ";
count++;
}
if ( isset($arr['type']) ) {
$query .= (($count > 0)?"and":"where")." profile_member = '".$arr['type']."' ";
count++;
}
if ( isset($arr['year']) ) {
$query .= (($count > 0)?"and":"where")." profile_year = '".$arr['year']."' ";
count++;
}
if ( isset($arr['course']) ) {
$query .= (($count > 0)?"and":"where")." profile_course = '".$arr['course']."' ";
count++;
}
You need to add some If statements to only include search criteria if the information is filled in.
$query = "select * from fsb_profile"<br />
$subquery = ""<br />
If($_REQUEST['name') != "") {<br />
if($subquery == "") $subquery = "where "<br />
else $subquery .= "and "<br />
<br />
$subquery .= "profile_name = '" . $_REQUEST['name']<br/>
}
$query .= $subquery
You could continue to do that for all the items. Note that you can use a for statement and I would HIGHLY recommend parameterizing the search string to prevent SQL injection attacks. I have only include some of the code here for brevity.
This will search on ALL the criteria that is specified to find a result.