I have a HTML form that people can select some or all off to search a database for member profiles.
Some of the options are:
Male/Female
Age
Location
check boxes like intentions or interests
etc
I need to tailor a MySQL query to meet the selection the member has chosen.
I'm asking because I built a custom search like this before and it turned into a complete mess with multiple queries depending on what was selected.
Would it be best to just build one query and have parts that are added depending on what is selected?
Does anyone have a ruff example?
Database Schema:
I have a number of tables with the related information so I would need to use joins. That said everything works on one primary key PID so it would all join on this.
You could do something like this:
<?php
$whereClause = '';
if($_GET['gender'] == 'male'){
$whereClause .= ' AND gender = "M"';
}
if($_GET['age'] != ''){
$whereClause .= ' AND age = "'.$_GET['age'].'"';
}
?>
I would use an array:
$where = array();
if($_GET["gender"]!=""){
$clean = mysqli_escape_string($db, $_GET["gender"]);
array_push($where, "gender = '$clean'");
}
// etc...
$where = implode(" AND ", $where);
$sql = "SELECT * FROM table WHERE $where";
Related
We have a HTML search page, having multiple text fields to search.
The user can input as many values as he want in text field and on submit, the query should return appropriate results.
We have different tables as
candidate
candidate_contact
company
etc.
Example:
User enters like candidate should have java skills also lives in California but should not have experience less than 2 years.
These records can be in same or different tables (like skills and country in same table and exp in another table)
Its like including and excluding search result.
$query = array();
if (!empty($_POST['keyword_s_dec']))
{
$query[] = "candidate.cand_desc = '".mysql_real_escape_string($_POST['keyword_s_dec'])."'";
$join.="JOIN candidate_contact ON candidate.cand_desc=candidate_contact.cand_id";
//$join.="select * from candidate join candidate_contact ON candidate.cand_number=candidate_contact.cand_id WHERE candidate.cand_desc='".$_POST['keyword_s_dec']."'";
}
if (!empty($_POT['keyword_s_location']))
{
$query[] = "candidate_contact.cand_location = '".mysql_real_escape_string($_POST['keyword_s_location;'])."'";///edit
$join.=" AND JOIN candidate_contact ON candidate.cand_number=candidate_contact.cand_id";
}
//$condition = implode(' AND ', $query);
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate".$join.' where '.$condition;
where - candidate is my main table and candidate_contact is another table.
where -cand_desc is database column in candidate & keyword_s-dec is text field id.
where- cand_location is my database column in candidate_contact and keywors_s_location is text field id.
This code is being slightly guided by one of stack overflow member and we though this should be edit to get more precised to the problem.
SELECT candidate.*,candidate_contact.feild_name1,candidate_contact.feild_name2
FROM candidate
LEFT JOIN candidate_contact
ON candidate.cand_number=candidate_contact.cand_id where $condition
Note:- add the table name with .(dot)in the where clause to define which feild name you want to do the comparision as shown in selection field area of the query and can continue joinning different tables in the same way as above before the where clause.
Hope this will solve your problem
if (!empty($_POST['keyword_s_dec']))
{
$query[] = "candidate.cand_desc = '".mysql_real_escape_string($_POST['keyword_s_dec'])."'";
$join.=" JOIN candidate_contact ON candidate.cand_number=candidate_contact.cand_id";
}
if (!empty($_POST['keyword_s_preflocation']))
{
$query[] = "candidate_contact.cand_location = '".mysql_real_escape_string($_POST['keyword_s_preflocation'])."'";///edit
//$join.=" LEFT JOIN candidate_contact ON candidate.cand_number=candidate_contact.cand_id";
}
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate ".$join.' where '.$condition;
#karvin.developer If the join condition gets same it won't work. I made some mistakes but re-read your statements from the start and it worked for me like heaven. Thank you karvin.developer :)
I have a question that I can't find an answer to it.
I want the user to enter words and on every ENTER press I send the word(s) to the server to search
I need my sql to search in 3 tables:
Products table:
PRODUCT NAME, PRODUCT DESCRIPTION, PRODUCT TAGS
User table:
USERNAME, USER EMAIL
user-info table:
ADDRESS, LANGUAGE
Let's say that
$d = array('0'=>'cell phone','1'=>'lightweight','2'=>'brasil','3'=>'nokia');
I need that all the SQL will search for everything everywhere
This is the closest I have arrived, I'm looking in only one table and one coll, I have no idea what to do.
public function getAllByTags($d){
$sql = 'SELECT * FROM '.TBL_WORKS.' WHERE tags ';
for($i = 0; $i < sizeof($d);$i++){
$sql .= 'LIKE \'%'.$d[$i].'%\'';
if(sizeof($d) != 1 && $i != sizeof($d)-1 && $i != sizeof($d)){
$sql .= ' OR ';
}
}
$query = $this->db->query($sql);
foreach($query->result_array() as $row){
$q[] = $row;
}
return $q;
}
I'm sure there's an answer somewhere in google but my English is not that good (i think :/),
Thank you for your help
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE %yourstring
you can do the search above on multiple columns
and if you want to do it on multiple tables you can run 3 subqueries and use union.
see here
I have a table called news and with these two snippets of code, I want to create a search engine that scans through the keywords table. With one table connected and running very nicely, it would be cleaner to add an extra table to the query.
My task is to create a search engine that returns rows from the tables. The search engine is based on keywords and is great for specific terming, such as 'New York Times' but if I want to type in news, that's where all the news sites are ordered by id. But sometimes completely different terms that have the keyword 'news' will pop up quite high in the table unlike CNN because of the id. With a new table, it would be a lot easier to organize the tables. That way if a term entered is 'news', sites will be ordered by id and even if they clash on other tables, they are still ordered by id.
Though my query is a bit different than the traditional query, I don't know how to
add a table via a UNION or
with a LEFT JOIN tag of some sort.
My query is below and I would love for someone to explain: a) what's wrong simply b) tell me or paste the code below:
<?php
if( isset($_GET['k']) ){
$k = $_GET['k'];
}else{
$k = '';
}
$k = ( isset($_GET['k']) )? trim($_GET['k']) : '';
$terms = (strlen($k) > 0)? explode(' ', $k) : Array();
/* The code below is from a different part of the script */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "keywords LIKE '%{$each}%'";
}
I don't know exactly what you want to do, but this might help :
$query = " SELECT * FROM scan, news WHERE scan.news_id = news.id AND ";
$terms = array_map('mysql_real_escape_string', $terms);
foreach ($terms as $each) {
$query .= "AND scan.keywords LIKE '%{$each}%'";
}
You make an union between two table by adding a condition in the query and selecting from the two tables. The condition is to ensure that the common column in the two tables are equals.
For a left join, read this http://www.w3schools.com/sql/sql_join_left.asp
I don't really know what you're asking. If you can clarify your question, I will provide an example for you. Thanks.
Trying to get a wildcard search to pick up on any text in org_name field and also to pick up any INT fields that have a 1 in them are entered into the form,
e,g If someone types Childminder in the form I want all records with the childminder INT field with a 1 in it to show up on the results...
$sql_result= "SELECT * FROM table WHERE org_name LIKE '%" . $org_name . "%'
OR carer LIKE '1'
OR childminder LIKE '1' ";
Not sure why you would do such things, but sounds like a candidate to the manual query concatenation (hint: don't do this, it hurts). PDO does not support binding column names, so you're out of luck if you're trying to have any help from libraries / other estabilished solutions.
Update
If your schema does not change and you're concerned about SQLi, you could have some matching mechanism that would take search query and array of available ("matchable") columns and process them, reporting matching columns. Then you would just make query from the safe data. Sample code:
$columns = array(/* ... */);
$query = '/* ... */';
$matches = array();
foreach($columns as $column)
{
if(preg_match('/'.$column.'/', $query))
{
$matches[] = $column;
}
}
$sqlQuery = 'you select';
foreach($matches as $match)
{
$sqlQuery .= ' OR '.$match.' = 1';
}
Not exact code, but you should get the idea.
Been searching all over for this but cant find an answer so thought I would ask here.
I have 5 drop down 'option box' lists whose data is populated from a database. The database information is about a user selecting a computer manufacture from the first drop down list, a computer type from the second, a computer colour from the third and finally a minimum and maximum price from the fourth and fifth drop down lists.
These user selected variables are then posted to a php 'search' page and a query is run on them. My question is, if (for example) a user only selected a computer 'manufacture' and 'make' and left all the other option boxes blank, how would I run this on my SQL search? Would I need to set then 'non set' variables as wildcards?
Any help would be appreciated!
You can build your query dynamically, something like this:
$sql = "SELECT ... FROM ... WHERE 1=1 ";
if ($manufacturer != "") {
$sql .= " AND manufacturer = ...";
}
if ($computerType != "") {
$sql .= " AND computerType = ...";
}
// etc...
SELECT * FROM TABLE WHERE
COLUMN_NAME_1 = IF('".$select_result_1."'='',COLUMN_NAME_1,'".$select_result_1"') AND
COLUMN_NAME_2 = IF('".$select_result_2."'='',COLUMN_NAME_2,'".$select_result_2"') AND
COLUMN_NAME_3 = IF('".$select_result_3."'='',COLUMN_NAME_3,'".$select_result_3"') AND
COLUMN_NAME_4 = IF('".$select_result_4."'='',COLUMN_NAME_4,'".$select_result_4"') AND
COLUMN_NAME_5 = IF('".$select_result_5."'='',COLUMN_NAME_5,'".$select_result_5"');