I want to create a search form for my site and be able to search by selecting multiple parameters, using LIKE and eventually ORDER BY. Search by name, country and date.
InnoDB, collation utf8mb4_unicode_ci, php 5.6
<?php
if(isset($_POST['search'])){
$sql = 'SELECT * FROM radio_posts';
$where = array();
$params = array();
if (!empty($_POST['postRadioName'])) {
$where[] = "postName LIKE :searchRadioName";
$params[':searchRadioName'] = '%'.$_POST['postRadioName'].'%';
}
if (!empty($_POST['postCountryID'])) {
$where[] = "postCountryID = :postCountryID";
$params[':postCountryID'] = $_POST['postCountryID'];
}
if (!empty($where)) {
$sql .= ' WHERE (' . implode(') AND (', $where) . ') ' ;
}
$stmt = $db->prepare($sql);
foreach($params as $param => $value) {
$stmt->bindParam($param, $value);
}
$stmt->execute();
}
?>
My table is radio_posts, there are also a few columns, postID, postName, postCountryID, postDate. In postName I have few rows: new radio, new radio 2, new radio 3. When I search for a term, for example "new", all three rows are displayed, good. If I search by postCountryID, for example "3" only one row is displayed, also good because only one is assigned to id 3. But when I search both, postName "new" and postCountryID "3" no results are displayed. How to solve this? to display the row/s coresponding to both, postName and postCountryID. In phpMyAdmin is working but using the search form it doesn't work:
SELECT * FROM `radio_posts` WHERE postName LIKE '%new%' AND postCountryID = 3
Also, if possible, I would like to ask, what is the best approach to order the results by postDate column, ascending, descending.
After replacing $stmt->bindParam($param, $value); with $stmt->bindValue($param, $value); the code is working as expected. One result is retrieved for the term "new" and country ID = 3.
Related
I want to fetching Records On the Basis Of Entered Keywords in the Search Bar.
Suppose I have Below 3 Records in My SQL Table's Column
Beautiful Small Kid.
Beautiful Rabbit in the Zoo.
Natural Water.
Now, If the Search Query contains Beautiful, It will Return First 2 Records.
If the Search Query contains Beautiful (anything), It will Return Nothing.
I want those First 2 Records to be Displayed in this case too, Because It has the same word beautiful like in above searched Query.
Right Now, I am Using
SELECT * FROM table WHERE name LIKE '%value%' ORDER BY id ASC
Is there any Other Query or Method to Achieve Such Sort Of Results ?
SELECT * FROM table WHERE (name LIKE '%value1%') OR (name LIKE '%value2%') ORDER BY id ASC
etc
So, you would have to split up your search string into separate words.
$str = yourinput;
$strarray = (explode(" ",$str));
$query = "SELECT * FROM table WHERE ";
Foreach($strarray as $key=>$value){
If($key > 0){
$query = $query . "OR";
}
$query = $query . " (name LIKE '%" . $value . "%') ";
}
$query = $query . "ORDER BY id ASC";
In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC
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";
I have test table which is
this is my table i am comparing string and getting the entity_id from this table
my sql query for one value search is like this
Select entity_id From test Where BINARY value = '".$my_search_list."'
this works fine if i search for single value like Shirt
i want to search for multiple values and when i try it with Comma Separated value
like Root,Appare,hand Bags (more than work) it is not giving me output
i Also tried with this
Select entity_id From test Where BINARY value IN ( '".$my_search_list."' )
i don't want multiple query i want to do it in single query is it possible???
what i was thinking as i said is to create an array of keywords and see which one match the criteria then show all result.
$search = array('Root','Appare','hand Bags');
$sql = "SELECT `entity_id` FROM `test` WHERE ";
$count = 0;
$search_size = count($search);
foreach($search as $key)
{
$count++;
if($count < $search_size)
{
$sql .= "(`value` = '".$key."') or ";
}
else if ($count == $search_size)
{
$sql .= "(`value` = '".$key."')";
}
}
is you echo $sql you will see the correct query wich should work:
SELECT `entity_id` FROM `test` WHERE (`value` = 'Root') or (`value` = 'Appare') or (`value` = 'hand Bags')`
you need to use quotes for values
SELECT entity_id FROM test WHERE value IN ('one','two','three')
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.