When I search any record by chapter number then it works.
But the problem is when I select chapter number 1 or 2 from drop-down and the search all records included in that chapter.
It displays all records included in 1,11,21,31...or 2,21,12,...like this.
I know I wrote 'like' there that's why it happens. But when i write " = " operator that I commented in my code that also didn't work for me.
What will be the perfect query to solve this problem?
My Code:
<?php
include("conn.php");
$name=$_POST['fname'];
$name2=$_POST['chapter'];
$sql="SELECT distinct * FROM $user WHERE question like '%".$name."%' and Chapter like '%".$name2."%'";
// $sql="SELECT * FROM $user WHERE question='$name' and Chapter='$name2'";
$result=mysql_query($sql,$connection) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
?>
I would be interested to see what the type of 'Chapter' is in the returned query, and try to see why it is that the equality comparison doesn't work.
If the typing is straightforward (i.e. it really is just plain old strings), then I'd be looking for whitespace characters or something like that which is foiling the equality comparison.
Similarly, I'm wondering whether it's the equality on the 'Question' that is messing up your alternate query.
At a guess, try one of the following:
$sql="SELECT distinct * FROM $user WHERE question like '%".$name."%' and Chapter like '$name2'";
$sql="SELECT distinct * FROM $user WHERE question like '%".$name."%' and Chapter='$name2'";
Oh, and you should really do something about escaping those parameters properly to avoid any nasty SQL injection attacks.
The problem is this part of the first query:
Chapter like '%".$name2."%'
If = doesn't work, then I can think of two things. The first is that Chapter is really a list, probably a comma delimited list. The second is that there are extraneous characters in the database.
If Chapter is really a list, use find_in_set() instead:
find_in_set($name2, Chapter) > 0
You directly use $_POST variables in your SQL query which makes you vulnerable to SQL injection attacks. Please take a look at this page for ways around that: http://bobby-tables.com/php.html. You should use either mysql_real_escape_string or prepared statements (better). The best solution would probably be to use PDO.
Also if you want a better answer, please format your question so it can be easily read, include example inputs, outputs and database contents and make sure your code is properly indented.
All I can assume now is that your database field probably contains more than the data you want to match. Leading/tailing spaces or something?
The main problem in your query is in this section
like '%".$name."%'
Just remove % sign from your whole query where you have wrote and check your query may work
properly.
Related
I have a table dictionary which contains a list of words Like:
ID|word
---------
1|hello
2|google
3|similar
...
so i want if somebody writes a text like
"helo iam looking for simlar engines for gogle".
Now I want to check every word if it exists in the database, if not it should
get me the similar word for the word. For example: helo = hello, simlar = similar, gogle = google.
Well, i want to fix the spelling errors. In my database i have a full dictionary of all english words. I coudn't find any mysql function which helps me. LIKE isn't helpfull in my situation.
you can use soundex() function for comparing phonetically
your query should be something like:
select * from table where soundex(word) like soundex('helo');
and this will return you the hello row
There is a function that does roughly want you want, but it's intensive and will slow queries down. You might be able to use in your circumstances, I have used it before. It's called Levenshtein. You can get it here How to add levenshtein function in mysql?
What you want to do is called a fuzzy search. You could use the SOUNDEX function in MySQL, documented here:
http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_soundex
You query would look like:
SELECT * FROM dictionary where SOUNDEX(word) = SOUNDEX(:yourSearchTerm)
... where your search term is bound to the :yourSearchTerm parameter value.
A next step would be to try implementing and making use of a Levenshtein function in MySQL. One is described here:
http://www.artfulsoftware.com/infotree/qrytip.php?id=552
The Levenshtein distance between two strings is the minimum number of
operations needed to transform one string into the other, where an
operation may be insertion, deletion or substitution of one character.
You might also consider looking into databases that are aimed at full text searching, such as Elastic Search, which provides this natively:
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html
I have a table dictionary which contains a list of words Like:
ID|word
---------
1|hello
2|google
3|similar
...
so i want if somebody writes a text like
"helo iam looking for simlar engines for gogle".
Now I want to check every word if it exists in the database, if not it should
get me the similar word for the word. For example: helo = hello, simlar = similar, gogle = google.
Well, i want to fix the spelling errors. In my database i have a full dictionary of all english words. I coudn't find any mysql function which helps me. LIKE isn't helpfull in my situation.
you can use soundex() function for comparing phonetically
your query should be something like:
select * from table where soundex(word) like soundex('helo');
and this will return you the hello row
There is a function that does roughly want you want, but it's intensive and will slow queries down. You might be able to use in your circumstances, I have used it before. It's called Levenshtein. You can get it here How to add levenshtein function in mysql?
What you want to do is called a fuzzy search. You could use the SOUNDEX function in MySQL, documented here:
http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_soundex
You query would look like:
SELECT * FROM dictionary where SOUNDEX(word) = SOUNDEX(:yourSearchTerm)
... where your search term is bound to the :yourSearchTerm parameter value.
A next step would be to try implementing and making use of a Levenshtein function in MySQL. One is described here:
http://www.artfulsoftware.com/infotree/qrytip.php?id=552
The Levenshtein distance between two strings is the minimum number of
operations needed to transform one string into the other, where an
operation may be insertion, deletion or substitution of one character.
You might also consider looking into databases that are aimed at full text searching, such as Elastic Search, which provides this natively:
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html
I am learning MySQL/php through online tutorials and have found the techniques and syntax different from different sources.
In one tutorial, I enter data (from an HTML form) like this:
$table = "ENTRIES";
$sql = "INSERT INTO $table SET
TITLE = '$_POST[title]',
SUMMARY = '$_POST[summary]',
CONTENT = '$_POST[content]'";
$query = #mysql_query($sql);
And in another, like this:
mysql_query("
INSERT INTO `posts` SET
`title` = '{$_POST['title']}',
`contents` = '{$_POST['post']}'
");}
They both work, and I understand the different variable arrangements. BUT I have the following questions, probably all related. (I gather that #mysql_query suppresses error messages, SO if that is what is going on here, can you please explain how it is functioning and what is actually proper syntax?)
1) In the first example, in #mysql_query(), it doesn't matter if I use ("") or ('') ... but in the second example, in mysql_query(), it breaks if I use (''). In fact it tells me that there is an unexpected {, which leads to my next question:
2) What is the deal with the {} in the second example? They don't seem to be doing anything, but it breaks without them.
3) In the first example, is breaks if I enclose title, summary, and content in single quotes ''. In the second, with 'title' and 'post', it breaks if I don't!
Any explanations or references/links comprehensible to a beginner would be much appreciated!
Run far away from this tutorial and fine one that uses PDO / mysqli and explains how to properly parameterize queries.
Anyway, your questions are PHP specific and have to do with variable interpolation in strings. In quoted strings (") variables are interpolated, and arrays can be accessed via:
"{$var['value']}"
"$var[value]"
Either one is valid ... they function identically and it's up to personal preference which one you should use.
mysql_query takes a string as an argument, so it actually makes no difference how you build it. Both of the above are valid. Using # makes no difference -- in fact, you shouldn't use it, and you should properly handle possible errors and check mysql_error
(Sorry for the longish question, I'll try to be concise.)
I'm running SQL Server Profiler and I'm chasing down some performance issues. I'm relatively new to what the profiler does and I've exported the traces into a table so I can run queries against the data.
One thing I've been running up against is some seemingly odd behavior doing select queries against the TextData field of the table generated by the trace export. It may have to do with the field's data type (ntext, null). I'm selecting for particular values, but getting unexpected results. For example, if I do this:
select * from [TraceAnalyzer].dbo.TraceTable
and I'm interested in values like this:
exec [Sproc_of_interest] #parm1=992
I'd do a query like this:
select * from [TraceAnalyzer].dbo.TraceTable
where TextData like '%exec [Sproc_of_interest] #parm1=%'
but the return result is empty.
Also, if I do a query like:
select * from [TraceAnalyzer].dbo.TraceTable
where TextData like '%exec [Sproc_of_interest]%'
I get unexpected TextData values like exec sp_reset_connection
Would the square brackets in the criteria be messing things up? I've tried omitting them, but that just excludes everything. I'm not aware of escape characters in SQL select queries, but when I copy/paste the value from one of the offending records, the pasted value does not appear to contain anything that would meet the original query's criteria.
Any insights would be greatly appreciated. Thanks.
[Sproc_of_interest] in the pattern syntax is interpreted as matching one character that is in the set S,p,r,o,c,_,o,f,_,i,n,t,e,r,e,s,t.
Three possible ways of solving this are below.
1) Escape [ with square brackets
LIKE '%exec [[]Sproc_of_interest] #parm1=%'
2) Use an escape character
LIKE 'exec \[Sproc_of_interest] #parm1=' ESCAPE '\'
3) Use CHARINDEX instead of escaping anything
WHERE CHARINDEX('exec [Sproc_of_interest] #parm1=' , TextData) > 0
I need some help with a RegEx. The concept is simple, but the actual solution is well beyond anything I know how to figure out. If anyone could explain how I could achieve my desired effect (and provide an explanation with any example code) it'd be much appreciated!
Basically, imagine a database table that stores the following string:
'My name is $1. I wonder who $2 is.'
First, bear in mind that the dollar sign-number format IS set in stone. That's not just for this example--that's how these wildcards will actually be stored. I would like an input like the following to be able to return the above string.
'My name is John. I wonder who Sarah is.'
How would I create a query that searches with wildcards in this format, and then returns the applicable rows? I imagine a regular expression would be the best way. Bear in mind that, theoretically, any number of wildcards should be acceptable.
Right now, this is the part of my existing query that drags the content out of the database. The concatenation, et cetera, is there because in a single database cell, there are multiple strings concatenated by a vertical bar.
AND CONCAT('|', content, '|')
LIKE CONCAT('%|', '" . mysql_real_escape_string($in) . "', '|%')
I need to modify ^this line to work with the variables that are a part of the query, while keeping the current effect (vertical bars, etc) in place. If the RegEx also takes into account the bars, then the CONCAT() functions can be removed.
Here is an example string with concatenation as it might appear in the database:
Hello, my name is $1.|Hello, I'm $1.|$1 is my name!
The query should be able to match with any of those chunks in the string, and then return that row if there is a match. The variables $1 should be treated as wildcards. Vertical bars will always delimit chunks.
For MySQL, this article is a nice guide which should help you. The Regexp would be "(\$)(\d+)". Here's a query I ripped off the article:
SELECT * FROM posts WHERE content REGEXP '(\\$)(\\d+)';
After retrieving data, use this handy function:
function ParseData($query,$data) {
$matches=array();
while(preg_match("/(\\$)(\\d+)/",$query,$matches)) {
if (array_key_exists(substr($matches[0],1),$data))
$query=str_replace($matches[0],"'".mysql_real_escape_string($data[substr($matches[0],1)])."'",$query);
else
$query=str_replace($matches[0],"''",$query);
}
return $query;
}
Usage:
$query="$1 went to $2's house";
$data=array(
'1' => 'Bob',
'2' => 'Joe'
);
echo ParseData($query,$data); //Returns "Bob went to Joe's house
If you aren't sticky about using the $1 and $2 and could change them around a bit, you could take a look at this:
http://php.net/manual/en/function.sprintf.php
E.G.
<?php
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
printf($format, $num, $location);
?>
If you want to find entries in the database, then you can use a LIKE statement:
SELECT statement FROM myTable WHERE statement LIKE '%$1%'
Which will find all statements that include $1. I'm assuming that the first number to replace will always be $1 - it doesn't matter, in that case, that the total number of wildcards is arbitrary, as we're just looking for the first one.
The PHP replacement is a little trickier. You could probably do something like:
$count = 1;
while (strpos($statement, "$" . $count)) {
$statement = str_replace("$" . $count, $array[$count], $statement);
}
(I've not tested that, so there might be typos in there, but it should be enough to give the general idea.)
The one downside is that it will fail if you have more than ten parameters in your string to replace - the first runthrough will replace the first two characters of $10, as it's looking for $1.
I asked a different, but similar, question, and I think the solution applies to this question just as well.
https://stackoverflow.com/a/10763476/1382779