PHP search to match all if the term is empty - php

I have written a simple search algorithm for my advanced search of my website.
There are several categories that the advanced search helps the user to limit his/her search. %$variable% is the matching that I use. I want the database to return every possible matches if the title is empty...what should be added/removed to/from this code?
if(isset($_POST['type']) && $_POST['type'] != 0)
{
$type = $_POST['type'];
if($wh == true)
{
$statement .= " AND `type` = '$type' ";
}
else
{
$wh = false;
$statement .= " WHERE `type` = '$type' ";
}
}
if(isset($_POST['sex']) && $_POST['sex'] != 0)
{
$sex = $_POST['sex'];
if($wh == true)
{
$statement .= " AND `sex` = '$sex' ";
}
else
{
$wh = false;
$statement .= " WHERE `sex` = '$sex' ";
}
}
if(isset($_POST['start']) && $_POST['start'] != 0)
{
$start = $_POST['start'];
if($wh == true)
{
$statement .= " AND `start` > '$start' ";
}
else
{
$wh = false;
$statement .= " WHERE `start` > '$start' ";
}
}
if($wh==true)
{
$statement .= " $branch_sentence AND( `title` LIKE '%$search_term%' OR `content` LIKE '%$search_term%' OR `keywords` LIKE '%$search_term%') ORDER BY stars DESC ";
}
else
{
$statement .= " WHERE `title` LIKE '%$search_term%' OR `content` LIKE '%$search_term%' OR `keywords` LIKE '%$search_term%' ORDER BY stars DESC ";
}
// echo $statement;
if($transorder = $site_db->query($statement))
{
$i=0;
while($row_obj = $transorder->fetch_object())
{
$item[$i]['id'] = $row_obj->id;
$item[$i]['pic_main'] = $row_obj->pic_main;
$item[$i]['title'] = $row_obj->title;
$item[$i]['province'] = $row_obj->province;
$item[$i]['stars'] = $row_obj->stars;
$i++;
}
}
}
}

What's wrong with:
if (empty($_POST['title']))
{
$statement = "SELECT id, pic_main, title, province, stars FROM "; // Incomplete b/c I don't know your table name from the question.
}
?

Related

Select Filter From Multiple Tables

I have a user chat system that has 2 tables: users table and followers table. I am performing a search and i want to get users that i am following
the users table has this as the primary key: user_id and the followers table has the following columns following_id follower_id is_typing active
How do i join the two tables to get my result?
I have been doing this:
function Wo_GetNearbyFriends($args = array()) {
global $wo, $sqlConnect;
if ($wo['loggedin'] == false || empty($args)) {
return false;
}
$options = array(
"offset" => false,
"gender" => false,
"name" => false,
"distance" => false,
"relship" => false,
"status" => false,
"fid_5" => false,
"fid_6" => false,
"fid_7" => false,
"fid_8" => false,
"limit" => 20
);
$args = array_merge($options, $args);
$offset = Wo_Secure($args['offset']);
$gender = Wo_Secure($args['gender']);
$name = Wo_Secure($args['name']);
$loc_distance = Wo_Secure($args['distance']);
$status = Wo_Secure($args['status']);
$relship = Wo_Secure($args['relship']);
$fid_5 = Wo_Secure($args['fid_5']);
$fid_6 = Wo_Secure($args['fid_6']);
$fid_7 = Wo_Secure($args['fid_7']);
$fid_8 = Wo_Secure($args['fid_8']);
$limit = Wo_Secure($args['limit']);
$unit = 6371;
$user_lat = $wo['user']['lat'];
$user_lng = $wo['user']['lng'];
$user = $wo['user']['id'];
$t_users = T_USERS;
$t_followers = T_FOLLOWERS;
$distance = 25;
$data = array();
$sub_sql = "";
if ($loc_distance && is_numeric($loc_distance) && $loc_distance > 0) {
$distance = $loc_distance;
}
if ($name) {
$name = Wo_Secure($name);
$sub_sql .= " AND (`username` LIKE '%$name%' OR `first_name` LIKE '%$name%' OR `last_name` LIKE '%$name%') ";
}
if (isset($status) && $status != false) {
if ($status == 1) {
$time = time() - 60;
$sub_sql .= " AND `lastseen` > '$time'";
} else if ($status == 0) {
$time = time() - 60;
$sub_sql .= " AND `lastseen` < '$time'";
}
}
if ($relship && in_array($relship, array_keys($wo['relationship']))) {
$sub_sql .= " AND `relationship_id` = '$relship' ";
}
if ($offset && is_numeric($offset) && $offset > 0) {
$sub_sql .= " AND `user_id` < '$offset' AND `user_id` <> '$offset' ";
}
if ($gender && in_array($gender, array_keys($wo['genders']))) {
$sub_sql .= " AND `gender` = '$gender' ";
}
if($fid_5 && is_numeric($fid_5) && $fid_5 > 0){
$sub_sql .= " AND `fid_5` = '$fid_5' ";
}
if($fid_6 && is_numeric($fid_6) && $fid_6 > 0){
$sub_sql .= " AND `fid_6` = '$fid_6' ";
}
if($fid_7 && is_numeric($fid_7) && $fid_7 > 0){
$sub_sql .= " AND `fid_7` = '$fid_7' ";
}
if($fid_8 && is_numeric($fid_8) && $fid_8 > 0){
$sub_sql .= " AND `fid_8` = '$fid_8' ";
}
$sql = "SELECT `user_id`, ( {$unit} * acos(cos(radians('$user_lat')) * cos(radians(lat)) * cos(radians(lng) - radians('$user_lng')) + sin(radians('$user_lat')) * sin(radians(lat))) ) AS distance FROM $t_users WHERE `user_id` <> '$user' {$sub_sql} AND `user_id` IN (SELECT `follower_id` FROM $t_followers WHERE `follower_id` <> {$user} AND `following_id` = {$user} AND `active` = '1') AND `user_id` IN (SELECT `following_id` FROM $t_followers WHERE `follower_id` = {$user} AND `following_id` <> {$user} AND `active` = '1') AND `lat` <> 0 AND `lng` <> 0 HAVING distance < '$distance' ORDER BY `user_id` DESC LIMIT 0, $limit ";
$query = mysqli_query($sqlConnect, $sql);
while ($fetched_data = mysqli_fetch_assoc($query)) {
$fetched_data['user_data'] = Wo_UserData($fetched_data['user_id']);
$fetched_data['user_data']['age'] = Wo_GetUserCountryName($fetched_data['user_data']);
$fetched_data['user_geoinfo'] = $fetched_data['user_data']['lat'] . ',' . $fetched_data['user_data']['lng'];
if ($fetched_data['user_data']['share_my_location'] == 1) {
$data[] = $fetched_data;
}
}
return $data;
}
Here is the mere join. Once you have the two user rows you can apply the distance calculation on their data.
select *
from t_users u1
join t_users u2
on u1.user_id < u2.user_id
and (u1.user_id, u2.user_id) in (select follower_id, following_id from t_followers)
and (u1.user_id, u2.user_id) in (select following_id, follower_id from t_followers);
Demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=f29e1d27055575385d4b28d777fd335c

MYSQL multiple words search result

When I type about three keywords or more it seems to only search the first keyword i.e bolt nut washer it will only search bolt.
I would like to search multiple keywords or the complete search term when inputted.
This is the code:
if (!(isset($_GET['pagenum']))) {
$pagenum = 1;
} else {
$pagenum = $_GET['pagenum'];
}
$page_limit = ($_GET["show"] <> "" && is_numeric($_GET["show"]) ) ? $_GET["show"] : 8;
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword OR contact_no1 LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
$stmt->execute();
$total_count = count($stmt->fetchAll());
$last = ceil($total_count / $page_limit);
if ($pagenum < 1) {
num < 1) {
} elseif ($pagenum > $last) {
$pagenum = $last;
}
$lower_limit = ($pagenum - 1) * $page_limit;
$lower_limit = ($lower_limit < 0) ? 0 : $lower_limit;
$sql2 = $sql . " limit " . ($lower_limit) . " , " . ($page_limit) . " ";
$stmt = $DB->prepare($sql2);
if ($keyword <> "" ) {
$stmt->bindValue(":keyword", $keyword."%");
$stmt->execute();
$results = $stmt->fetchAll();
}
} catch (Exception $ex) {
echo $ex->getMessage();
}
I figured it out. Fixed by changing:
. " (first_name LIKE :keyword OR contact_no1 LIKE :keyword) ORDER BY first_name ";
to
. " (first_name LIKE '%".$keyword."%' OR contact_no1 LIKE '%".$keyword."%') ORDER BY last_name DESC ";
Now the search returns any keyword entered

search by multiple field. sometimes by one field and sometimes more than one field

I have search form. in here multiple field. sometimes I will form submit with one field, sometimes form submit with two and sometimes multiple field value.
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
if (!empty($projectName))
{
$searchSql = mysql_query("select * from project_list where projectName='$projectName'");
}
if (!empty($clientId))
{
$searchSql = mysql_query("select * from project_list where client_id='$clientId'");
}
if (!empty($departmentId))
{
$searchSql = mysql_query("select * from project_list where department_id='$departmentId'");
}
if (!empty($statusName))
{
$searchSql = mysql_query("select * from project_list where status='$statusName'");
}
}
these query only for search by single field.
how to make query that performs searching by one or multiple field value
is it possible??
Use Concatenation in query Variable
$searchSql ="select * from project_list where 1=1 ";
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
if (!empty($projectName))
{
$searchSql. = " AND projectName='$projectName'";
}
if (!empty($clientId))
{
$searchSql. = " AND client_id='$clientId'";
}
if (!empty($departmentId))
{
$searchSql. = " AND department_id='$departmentId'";
}
if (!empty($statusName))
{
$searchSql. = " AND status='$statusName'";
}
}
$result=mysql_query($searchSql);
NOTE:mysql_query() has been deprecated in PHP 5.5 and removed in PHP 7. Kindly update to use mysqli library of PDO.
You can build an increntale query
<code>
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
$my_sql = "select * from project_list ";
$my_where = "";
if (!empty($projectName))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "projectName='$projectName'";
}
if (!empty($clientId))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "client_id='$clientId'";
}
if (!empty($departmentId))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "department_id='$departmentId'";
}
if (!empty($statusName))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "status='$statusName'";
}
}
Here I used column id as primary key & auto-increment. Change it as per your column name.
$query = "SELECT * FROM project_list WHERE id is not null";
Code
<?
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
// Here I used coloumn 'id' as primary key & auto-increment. Change it as per your column name.
$query = "SELECT * FROM project_list WHERE id is not null"
if (!empty($projectName))
{
$query. = " AND projectName='".$projectName."'";
}
if (!empty($clientId))
{
$query. = " AND client_id='".$clientId."'";
}
if (!empty($departmentId))
{
$query. = " AND department_id='".$departmentId."'";
}
if (!empty($statusName))
{
$query. = " AND project_list='".$statusName."'";
}
$searchSql = mysql_query($query);
}

PHP MySQL search with multiple criteria

I have a search form in a website and would like to have several search terms which is input by the user to perform db search, terms as below:
Keywords
Property For (Sale, Rent...)
Property Type (Apartment, Terrace House...)
State
Min Price
Max Price
Here is script to perform search with above term's input
public function get_property_list_by_search($start, $per_page, $keyword, $prop_for, $min, $state, $ptype, $max, $mysqli)
{
if(empty($start) && empty($per_page))
{
return 0;
}
$start = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($start));
$per_page = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($per_page));
$keyword = $mysqli->real_escape_string(stripslashes($keyword));
$prop_for = $mysqli->real_escape_string(stripslashes($prop_for));
$state = $mysqli->real_escape_string(stripslashes($state));
$ptype = $mysqli->real_escape_string(stripslashes($ptype));
$min_price = self::num_clean($mysqli->real_escape_string($min));
$max_price = self::num_clean($mysqli->real_escape_string($max));
$t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
if(isset($keyword) && !empty($keyword)){
$t1 = " AND `proj_title` LIKE '%".$keyword."%' OR `proj_addr` LIKE '%".$keyword."%' OR `proj_area` LIKE '%".$keyword."%'";
}
if(isset($prop_for) && !empty($prop_for)){
$t2 = " AND `proj_for`='".$prop_for."'";
}
if(isset($state) && !empty($state)){
$t3 = " AND `state`='".$state."'";
}
if(isset($ptype) && !empty($ptype)){
$t4 = " AND `proj_cat`='".$ptype."'";
}
//min & max
if((isset($min_price) && !empty($min_price)) && (isset($max_price) && !empty($max_price))){
$t5 = " AND `price` BETWEEN '".$min_price."' AND '".$max_price."'";
}
//min only
if(!empty($min_price) && empty($max_price)){
$t5 = " AND `price` >= '".$min_price."'";
}
//max only
if(empty($min_price) && !empty($max_price)){
$t5 = " AND `price` <= '".$max_price."'";
}
$sql = $mysqli->query("SELECT * FROM `project` WHERE `status`='1' ".
$t1." ".$t2." ".$t3." ".$t4." ".$t5." ".
"ORDER BY `posted_date` DESC LIMIT ".$start.", ".$per_page);
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
The query output will something like:
SELECT * FROM `project`
WHERE `proj_title` LIKE '%keywords%'
OR `proj_addr` LIKE '%keywords%'
OR `proj_area` LIKE '%keywords%'
AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
(Datatype for price is DECIMAL(10,2), it stored value like 250000.00)
However, the returned results is not like expected (not accurate), its also will come out a result with price more than 600000 and project category which is out of '8' which is not fancy for the end user to searching in the website.
is there any way to refine on the query to perform more specific?
Instead of taking these variables you should use ".=" operator.
/* $t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
*/
$q = "SELECT * FROM `property` WHERE `status`='1' ";
// You need to enclose all **OR** logical tests in parenthesis.
// Moreover most of the usages of isset function are useless,
// as your are initializing many variables
if($keyword && !empty($keyword)){
$q .= " AND (`p_title` LIKE '%".$keyword."%' OR `address` LIKE '%".$keyword."%' OR `area` LIKE '%".$keyword."%')";
}
if($prop_for && !empty($prop_for)){
// If you are using double quotes you really don't need handle to concatenation.
$q .= " AND `p_for`='$prop_for'";
}
if($state && !empty($state)){
$q .= " AND `state`='$state'";
}
if($ptype && !empty($ptype)){
$q .= " AND `p_category`='$ptype'";
}
//min only
if($min_price && !empty($min_price)){
$q .= " AND `price` >= '".$min_price."'";
}
//max only
if($max_price && !empty($max_price)){
$q .= " AND `price` <= '$max_price'";
}
// When you are not using OFFSET keyword,
//the first number after LIMIT keyword should be the number of records
$q .= " ORDER BY `posted_date` DESC LIMIT $per_page , $start;";
$sql = $mysqli->query($q);
You're going to need parentheses.
SELECT * FROM `project` WHERE (`proj_title` LIKE '%keywords%' OR `proj_addr` LIKE '%keywords%' OR `proj_area` LIKE '%keywords%') AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
Without the parentheses it just has to match one of the criteria before the last OR.
if(isset($_SESSION['login']))
{
echo "<div align=\"right\"><strong> Home |
Signout|
Profile</strong></div>";
}
else
{
echo " ";
}
$con= mysql_connect("localhost","root","");
$d=mysql_select_db("matrimonial",$con);
$gender=$_POST['gender'];
$age1=$_POST['age1'];
$age2=$_POST['age2'];
$city=$_POST['city'];
$subcast=$_POST['subcast'];
$result=mysql_query("select * from matri where gender='$gender' and age between '$age1' and '$age2' and city='$city' and subcast='$subcast'");
if($gender && !empty($gender))
{
$result .= " AND `gender`='$gender'";
}
if($age1 && !empty($age1)){
$result .= " AND `age`='$age1'";
}
if($age2 && !empty($age2)){
$result .= " AND `age`='$age2'";
}
if($city && !empty($city)){
$result .= " AND `city`='$city'";
}
if($subcast && !empty($subcast)){
$result .= " AND `subcast`='$subcast'";
}
$result .= " select * from ";
$sql = $mysql->query($result);
how to run this code
On the price difference you should do a if the price if between the 2 values else only 1 value.

How to make one variable out of this?

Best,
I'm bussy making a website, but one thing holds me up..
I have to make a real long search query, and i have made this PHP code:
if($_GET['genre']) {
echo 'SELECT * FROM movies WHERE `genre1` = ';
foreach($_GET['genre'] as $genre)
{
$genres = array( "Actie", "Animatie", "Avontuur", "Documentaire", "Drama", "Erotiek", "Familie", "Fantasy", "Film", "Horror", "Komedie", "Misdaad", "Muziek", "Mystery", "Oorlog", "Roadmovie", "Romantiek", "Sciencefiction", "Thriller", "Western" );
if (!in_array($genre, $genres))
{
header('location: ?error=1');
}
echo " '".$genre."' OR `genre2` = '".$genre."'"; if(end($_GET['genre']) !== $genre)
{
echo ' OR `genre1` = ';
}
}
echo " AND `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
}
else
{
echo "SELECT * FROM movies WHERE `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
}
On a URL like this:
127.0.0.1/querygenerator.php?genre%5B3%5D=Avontuur&genre%5B4%5D=Documentaire&genre%5B6%5D=Erotiek&year1=1900&year2=2014
And it outputs something like this:
SELECT * FROM movies WHERE `genre1` = 'Avontuur' OR `genre2` = 'Avontuur' OR `genre1` = 'Documentaire' OR `genre2` = 'Documentaire' OR `genre1` = 'Erotiek' OR `genre2` = 'Erotiek' AND `year` > '1900' AND `year` < '2014';
So, my question is, how can i make one PHP variable out this whole, so I can run the query?
I can do this with file_get_contents but that's not so safe, I guess..
Thanks!
- Karim
Just concatenate to a string rater than echoing:
if($_GET['genre']) {
$sql = 'SELECT * FROM movies WHERE `genre1` = ';
foreach($_GET['genre'] as $genre) {
$genres = array( "Actie", "Animatie", "Avontuur", "Documentaire", "Drama", "Erotiek", "Familie", "Fantasy", "Film", "Horror", "Komedie", "Misdaad", "Muziek", "Mystery", "Oorlog", "Roadmovie", "Romantiek", "Sciencefiction", "Thriller", "Western" );
if (!in_array($genre, $genres)) {
header('location: ?error=1');
die();
}
$sql = $sql . " '".$genre."' OR `genre2` = '".$genre."'";
if(end($_GET['genre']) !== $genre) {
$sql = $sql . ' OR `genre1` = ';
}
}
$sql = $sql . " AND `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
} else {
$sql = "SELECT * FROM movies WHERE `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
}
echo $sql;

Categories