How to find a specific word in a MySQL table? - php

i want to find specific keyword in MySQL Table ....
The main code is:
if ($_REQUEST["keyword"]<>'') {
$search_string = "AND trainer like '".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR venue like '".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR session like '".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR course like '".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR category like '".mysql_real_escape_string($_REQUEST["keyword"])."%'";
}
else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]."
WHERE id>0".$search_string;
}
The problem is the code above shows same result for any word searched. Any help of reference will be much appreciated.

For whole specific word you need means you have to go through with double %% before and after the word
if ($_REQUEST["keyword"]<>'') {
$search_string = "AND trainer like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR venue like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR session like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR course like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR category like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'";
}
else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]."
WHERE id>0".$search_string;
}

Assuming your problem is that you're getting incorrect results, you can fix this with the following:
$search_string = " AND (trainer like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR venue like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR session like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR course like '%".mysql_real_escape_string($_REQUEST["keyword"])."%'
OR category like '%".mysql_real_escape_string($_REQUEST["keyword"])."%')";
Changes made:
Added brackets around your set of OR statements
Prepended the wildcard character to your search string, as well as the existing appended wildcard
Added a space before your AND so your resulting query doesn't end up containing id>0AND
Edit:
I thought I could help more by explaining what is going wrong. Assuming someone searches for 'foo' and your table is called 'bar', your code will generate the following query:
SELECT
*
FROM
bar
WHERE
id>0AND
trainer like 'foo%'
OR venue like 'foo%'
OR session like 'foo%'
OR course like 'foo%'
OR category like 'foo%'
There are a couple of problems here:
You have combined your parts incorrectly so AND winds up right next to 'id>0', a space before AND fixes that problem.
You haven't wrapped your set of OR statements in brackets, so you end up with a query that asks for ANY of the conditions to be met (including id > 0 by itself)
You have not prepended a wildcard character to the search string, meaning you will only find records that start with 'foo', and not records that contain 'foo' somewhere else.
The suggested changes above will fix these problems.

Related

search without hyphen in mysql

Mysql database contains below kind of values :
'AE01-1056 Ricoh Aficio' OR 'Ricoh AE01-1087 (AE01-1069)' etc
AS if am a normal user i will search the product name in simple text like
AE011056 ... but the result is not found.
i hav tried this query:
$q="SELECT * FROM mytable WHERE (p.product_name LIKE '$name%' OR c.category_name LIKE '$name%' OR pm.name LIKE '$name%')";
What change should i make in my query to get the product , because i have tried LIKE operator & it's not working for me.
Use replace function
$q="SELECT * FROM mytable
WHERE (REPLACE(p.product_name,'-','') LIKE '%$name%'
OR REPLACE(c.category_name,'-','') LIKE '%$name%'
OR REPLACE(pm.name ,'-','') LIKE '%$name%')";
I think there are only two ways:
1. Manipulate search string
If you knwo, users are often search for a code and don't use nessesary hyphens, check the searchstring bevor searching if it follows a given format an insert the hypen if it is missing.
2. replace all hyphens in the where-statement
see http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace
Depending on your setup, solution one might be the more performant solution, since you only have to do one instead multiple stringmanipulations.

How to build a MySQL query with conditional filters?

I'm pretty new to both PHP and MySQL and I'm trying to build a small library of singers' quotes. I'd like the user to be able to search for a quote by typing a part of the quote itself, the singer's name or the singer's band, if any.
Now, that part I pretty much nailed:
$query = 'SELECT * FROM quotes WHERE (quote LIKE "%'.$search_string.'%" OR singerName LIKE "%'.$search_string.'%" OR bandName LIKE "%'.$search_string.'%")';
This works, although it alors returns results where the search_string is in the middle of a word: if I type "her", it will return every quote containing "other" or "together". If I drop the second % from the query, it won't return quotes where the search_string isn't the very first word, which I want it to do.
Anyway, what I'd also like to do is give the possibility to filter the results. Let's say I want the user to be able to only show quotes in English, German or Both, via radio buttons. By default, Both is selected, so the $query above is still valid. However, if the user selects English, it should also say something like AND (language = 'EN').
For now, I tried adding to the query this way:
if ($_POST['language']== "EN") {
$sql .= " AND (language = 'EN')";
}
It works, but it can be a real hassle, as I also want the user to search for quotes using only the filters, without entering a search query: they would be able to look for quotes in English by singers in Band, for example. So, I also have this:
if (strlen($search_string) < 1) {
$sql = "SELECT * FROM quotes";
}
But then, the $sql .= " AND (language = 'EN')"; wouldn't be correct anymore, as "AND" should be "WHERE". So I'll have to have another if clause to modify the string, and another one for every filter I decide to apply.
My question is then: how should I build my query, given that there are optional filters, and that the search should also be possible using the filters alone?
Thanks!
Set an always true condition in order to have constant WHERE clause.
$sql = "SELECT * FROM myTable WHERE 1 = 1 "
if (true) {
$sql .= " AND col1 LIKE '%val%' ";
}

How do I search Full text with partial matches?

I have a table, with not many rows, and neither many columns. I am doing a Full text search on 3 columns.
My code is
$search_input = trim($_GET['s']);
$search = mysql_real_escape_string($search_input);
$search = '+'.str_replace(' ', '* +', $search).'*';
$sql = "SELECT * FROM table WHERE
MATCH(def, pqr, xyz) AGAINST ('$search' IN BOOLEAN MODE)";
$result = mysql_query($sql);
I can correctly search for terms like abcdefgh, which are present as ... abcdefgh ....
But I am receiving empty set with search terms like abc, where in table entry is present something like abc-123, and also terms like abcdefghs. (notice this is plural of above)
Clearly I need to implement partial search, or something like that.
But how do I implement such a search? Any better way to do a entire table search on user input?
Do mention anything I am doing incorrectly.
EDIT : By adding * after each word, now I am able to also search for abcde, but above problems remains.
Do you mean you don't get results for 3 letter combinations? If so, you might be hitting the mysql index length (which is usually set to 3)
More info here - http://dev.mysql.com/doc/refman/5.1/en/fulltext-fine-tuning.html

Why query is not working?

In model query -
public function get_articles_from_query($squery){
$query = DB::query(Database::SELECT, 'SELECT * FROM ieraksti WHERE virsraksts = "%:squery%" AND slug = "%:squery%" AND saturs = "%:squery%"')
->parameters(array(":squery" => $squery))->execute();
return $query;
}
Why this script is not working? I not have any errors, but blog articles not found.
Well, my first question is:
Do you have any rows that have that word, and nothing else, surrounded by % characters, in all three of the the title, content and slug (a)? This seems unlikely.
If not, the query will return no rows.
The use of the % wildcards is for like, not for =. If your squery word is banāns for example, your query will only match rows where all three columns are exactly the literal %banāns% value, not a value containing banāns somewhere within it.
I think you want:
SELECT * FROM ieraksti
WHERE virsraksts like "%:squery%"
AND slug like "%:squery%"
AND saturs like "%:squery%"
For your subsequent problem:
I understand the problem. I put in model var_dump($query); and it shows the query - SELECT * FROM ieraksti WHERE virsraksts like "%'ar'%" OR slug like "%'ar'%" OR saturs like "%'ar'%. The is not word 'ar', but ar. How to remove ' from query?
If that's the case, you will have to change your query to something like:
$query = DB::query(Database::SELECT,
'SELECT * FROM ieraksti WHERE virsraksts like :squery AND slug ...')
->parameters(array(":squery" => "%$squery%"))->execute();
In other words, move the attachment of the % characters to the parameter specification, not the query itself. From your debug, the parameters are automatically having single quotes wrapped around them so, if you want to do anything inside those quotes, you have to do it before the wrapping.
And you obviously don't need the double quotes in this case because that wrapping is taking place.
And check that line with "%$squery%" in it, I'm not sure it's the right syntax. I'd say my PHP was a bit rusty but, to be honest, I've only ever used it for about seven minutes in my whole life :-)
What you're aiming for is a string consisting of %, the value of $squery and another %.
(a) Man tiešām patīk, kā Google Translate padara mani izskatās es zinu desmitiem dažādās valodās :-)

PHP/SQL Statements - I understand the process but not the individual lines of code, can anyone help?

I have this code below on a website, it was written by someone else. I understand that it is taking the information that was entered in (company) and if the entry is empty it takes the user to companies.php page. If it is not empty it takes the entry and looks it up in the table.
The Bit I really do not understand is after the else, $Where Section, in particular the %, I thought that was when you make a comment??
Hope someone can help?
Thanks :)
if ($_POST["Company"] == "")
{
header("Location: companies.php?page=1");
$Orders = "<div id='ErrorMessage'>Please enter a company name or partial company name to search the Credit Report Shop.</div>\n";
}
else
{
$WhereSection="";
if ($_POST["Company"])
$WhereSection .= "WHERE UPPER(Company) LIKE '%".strtoupper($_POST["Company"])."%'";
$Statement = "SELECT * from jos_companies
$WhereSection
ORDER BY Company ASC, LastReport DESC";
db_connect();
$rid=mysql_query($Statement);
$rcount=0;
}
The % is a wildcard used in a LIKE clause in a SQL WHERE statement.
So if the value of company is 'ABC', LIKE '%ABC%' will match any value that contains 'ABC' either at the beginning, in the middle or at the end; LIKE 'ABC%' will match all values beginning with 'ABC' and LIKE '%ABC' will match all values ending in 'ABC'
And you should be escaping your $_POST fields before embedding them in SQL statements
The % is a wildcard character for the LIKE search.
So, for example, if the input was "don", then LIKE '%don%' would match names like "McDonalds" and "Donlen", etc.
$WhereSection .= "WHERE UPPER(Company) LIKE '%".strtoupper($_POST["Company"])."%'";
If there is information in $_POST['Company'] then we'd like to filter the query to match the company name. LIKE '%text%' will match for anything that has text in it. % is a wildcard that matches anything.
UPPER() is used to skip case sensitivity.
Good Luck

Categories