String comparisons in MySQL

I want to allow my PHP search engine to find records
containing characters that are special to MySQL. For example: if
right now I searched for "%", it would return every record in the
table because % is a MySQL wildcard. I want it to return records
that actually contain a % in the specified fields.
Other current unsearchable characters include ! @ # $ & (
...you get the idea.
How can I make all of these characters searchable in a real
MySQL string comparison?

.oO(AngryCloud)
>I just want a search engine that will search for any
given string within the
>specified fields, regardless of the characters in the
string. So if I search
>for $20, I want to see results where "$20", not just
"20", was actually found
>in the field.
That's what LIKE usually does. Its only special chars are the
wildcards
'%' and '_', which have to be escaped if you want to search
for them.
The rest should work fine.
> The concept of this string comparison is such a simple
one, yet MySQL does not
>seem to be very friendly with real string comparisons.
Don't blame it on MySQL, it usually does very well with such
things.
> You would think there would be some kind of PHP function
that would escape
>every character in a string to make the characters
readable to MySQL simply as
>parts of the string, rather than special MySQL
characters.
It would help to post some code and your query that fails.
Did you try
such a search query directly on the MySQL command line?
Micha

Similar Messages

  • [svn:bz-trunk] 18053: BLZ-571: Use of wrong operator in string comparison in flex.messaging.VersionInfo. java

    Revision: 18053
    Revision: 18053
    Author:   [email protected]
    Date:     2010-10-07 03:27:37 -0700 (Thu, 07 Oct 2010)
    Log Message:
    BLZ-571: Use of wrong operator in string comparison in flex.messaging.VersionInfo.java
    Updated the code to use the right operator.
    Check-in Tests: PASS
    QA: Yes
    Ticket Links:
        http://bugs.adobe.com/jira/browse/BLZ-571
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/VersionInfo.java

  • Fault in string comparisons?

    Hallo.
    I have the following problem. An XML file, encoded in ISO8859-2, should be presented in a table in a browser's window. The file is "one level deep", something like:
    <type>animal</type>
    <name>cat</name>
    <type>insect</type>
    <name>ant</name> ...and so on.
    The resulted table should be (its heading in bold):
    TYPE NAME
    animal cat
    insect ant
    I process the file using methods from 'org.w3c.dom.*' package and store all the strings (having polish national characters) in a table. The table is displayed correctly.
    Besides presentation of everything, the user should be able to select only certain rows from the table. To do this, he has input boxes (as many as the colums in the table) and can enter strings into them. These strings serve as filters. For example, after entering 'animal' in the first box only the first row of the table above should be displayed.
    Again, everything works fine, but only if the string entered doesn't contain polish characters. If it does - no one row is displayed.
    The application is made as a servlet with the XML file stored in the same server.The strings entered in the input boxes are displayed correctly (with polish characters). The caracters seem to be properly encoded (first the browser is set to use ISO8859-2, and, second, I see their values in the browser's address window when they are sent using GET). I tried PUT too - in vain.
    The polish characters in the test XML file were checked in hex editor and are surely encoded in ISO8859-2. The encoded type is declared in the files' header.
    So my questions are:
    1/ What is wrong?
    2/ What to do to correct it?
    Any suggestion(s) are highly appreciated.
    With many thanks in advance,
    L. Pankowski
    ([email protected])

    Sorry once more! Maybe the following version will be better?
    (By the way: Is it possible to remove improperly posted messages from the thread?)
    Regards,
    L.P.
    //from doGet method; doPost is the same as doGet
       DocumentBuilder builder;
       File f = new File("C:/servlets/test2.xml");
       try
          DocumentBuilderFactory factory
             = DocumentBuilderFactory.newInstance();
           factory.setValidating(true);
           factory.setIgnoringElementContentWhitespace(true);
          builder = factory.newDocumentBuilder();
    //Parse the content of the file as an XML document
    // and return a new DOM Document object..
       Document doc = builder.parse(f);
       Element root = doc.getDocumentElement();
       NodeList children = root.getChildNodes();
       int elementsNr = children.getLength();
    //Getting column names. Get the first one
    //and proceed until you find an identical one.
    //(there will be no more than 30 columns)
       String[] colNames = new String[30];
       Node first = children.item(0);
         Element firstElement = (Element)first;
         String firstColName = firstElement.getTagName();
         colNames[0] = firstColName;
         int n = 1;
         Node next = children.item(i);
         Element nextElement = (Element)next;
         String nextName = nextElement.getTagName();
         while (nextName != firstColName)
             colNames[n] = nextName;
             n++;
             next = children.item(i);
             nextElement = (Element)next;
             nextName = nextElement.getTagName();
          columnsNr = i;
          rowsNr = (int)elementsNr/columnsNr;
    //Array to put the strings that will be displayed
    // in the browser's table
          cells = new String[rowsNr][columnsNr];
    //Filling the array..
          for (n = 0; n <rowsNr ; n++)
             for (j = 0 ; j <columnsNr; j++)
                Node child = children.item(j+ n*columnsNr);
                Element childElement = (Element)child;
                Text textNode = (Text)childElement.getFirstChild();
                String text = textNode.getData().trim();
                cells[n][j] = text;
    //The content sent to the browser..
       response.setContentType("text/html; charset=iso-8859-2");
       PrintWriter out = response.getWriter();
       String title = "Library";
       out.println("<FORM method=\"POST\">");
       String napis = "To select certain rows fill in the fields and press" +
                            "<input type=\"submit\" value=\"Send\">";
       out.println(ServletUtilities.headWithTitle(title) +
                    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                    "<H5>" + napis + "</H5>\n");
       out.println("<H5>Empty field means don't care. To clear all the fields press <input type=\"reset\" value=\"Clear\"></H5>");
    //Getting elements of the filter..
    //The array to store elements of the filter sent from the browser
       String[] filterFields = new String[columnsNr];
    //Empty string means: don't check
       for (n = 0; n <columnsNr; n++)
          filterFields[n] = "";
       Enumeration sent = request.getParameterNames();
    //Not null fields' counter -
    // used to speed up the search of the matching rows (below)        
          k = 0;
       while (sent.hasMoreElements())
          String fieldName = (String)sent.nextElement();
          String fieldValue = request.getParameter(fieldName);
          if (fieldValue.length() > 0)
             n = 0;
             while (!fieldName.equals(colNames[n]))
             n++;
             filterFields[n] = fieldValue;
             k++;
    //Preparing and sending input fields of the filter..
       String filterBoxes = "";
    //Attempts to adjust the lengths of filter fields
    // to the resolution of the screen
       String dl = "size=\"" + (int)100/columnsNr + "%\"";
       for (n = 0; n <columnsNr; n++)
          filterBoxes = filterBoxes + "<input name=\"" + colNames[n] + "\"" + dl + "value=\"\">";
       filterBoxes = filterBoxes + "<BR>";
       out.println(filterBoxes);     
       out.println("</form>");
    //Forming and sending table header..
       String tableHeader = "";
       for (n = 0; n <columnsNr; n++)
          tableHeader = tableHeader + "<TH STYLE=\"width:1%;\">" + colNames[n];
       tableHeader = tableHeader + "</TH>";
       out.println("<TABLE BORDER=1>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + tableHeader);
    //Searching table rows matching the filter fields
    // and sending them to the browser..
    //n - row o the table being processed; j - column
       for (n = 0; n <rowsNr ; n++)
          j = 0;
          String row = "<TR>";
          boolean matches = true;
          int KCopy = k;
          while ((KCopy > 0) && matches)
          if (filterFields[j] == "")
             row = row + "<TD>" + cells[n][j];
             j++;
    //THIS IS WHERE THE STRING COMPARISON TAKES PLACE     
          else if ((filterFields[j]).equals(cells[n][j]))
               row = row + "<TD>" + cells[n][j];
               j++;
               KCopy--;
               else matches = false;
          if (matches)
             while (j < columnsNr)
              row = row + "<TD>" + cells[n][j];
              j++;
             out.println(row);
          out.println("<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
               "<TR BGCOLOR=\"#FFAD00\">\n" + "</BODY></HTML>");
    }

  • In string comparisons

    Hello,
    I'm new to java and was wondering how I could do an in-string comparison. I.E. check if the string "the" is in "here is the". In ASP you can write inStr(string 1, string2) and I was wondering what the JSP equivalent was.
    any help is appreciated!
    thanks,
    rob

    use---> s.indexOf("the");
    where s is your " here is the ". create it like this
    String s = new String("here is the ") l
    or
    String s = "here is the";
    the method return the index of first occurence of the string "the"
    if the index >=0 then "the" is present in your string s.
    there is no special method in JSP. U have to use java obejcts and methods only.

  • String comparison of big integers

    I need to compare big numbers in all number systems, but first step is to be able to compare them in decimal number system, which is not working properly, 
    e.g. 
               int Comparison = CompareNumbers("510", "228"); 
                if (Comparison == 0) 
                    MessageBox.Show("N1 = N2"); 
                else if (Comparison == 1)                 
                    MessageBox.Show("N1 > N2"); 
                else 
                    MessageBox.Show("N1 < N2"); 
    shows "N1 < N2" which is obviously WRONG 
    please don't care much about GetDigitValue function and the number systems as I am pretty sure this is OK 
    string Numbers = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    private Int16 GetDigitValue(char Digit) 
    Int16 Value = Convert.ToInt16(Numbers.IndexOf(Char.ToUpper(Digit))); 
    if (Value == -1) 
       throw new InvalidNumberSystem(); 
       else return Value; 
    private int CompareNumbers(string Number1, string Number2) 
    int I = -1; 
    Number1 = Number1.TrimStart('0'); 
    Number2 = Number2.TrimStart('0'); 
    if (Number1 == Number2)              return  0; else 
    if (Number1.Length < Number2.Length) return -1; else 
    if (Number1.Length > Number2.Length) return  1; else 
         do { 
             I++; 
         } while ((I < Number1.Length) && (GetDigitValue(Number1[I]) >= GetDigitValue(Number2[I]))); 
    if (I < Number1.Length - 1) 
         return -1; 
    else 
         return 1; 
    The error has to be in this code
         do { 
             I++; 
         } while ((I < Number1.Length) && (GetDigitValue(Number1[I]) >= GetDigitValue(Number2[I]))); 
    if (I < Number1.Length - 1) 
         return -1; 
    else 
         return 1; 

    I'm not sure what your goal is here or why you think you need BigInteger for this but you are merely reinventing string comparison. You are, after all, passing
    strings to CompareNumbers, not integers.
    I rewrote your code in a console test bed.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace ConsoleApplication1
    class Program
    static void Main(string[] args)
    int Comparison;
    Comparison = CompareNumbers("510", "228");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("228", "228");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("228", "510");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("2", "1");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("2", "2");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("1", "2");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("11111111111111111111111111111111111111111111111",
    "1111111111111111111111111111111111111111111111");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("11111111111111111111111111111111111111111111111",
    "11111111111111111111111111111111111111111111111");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("11111111111111111111111111111111111111111111111",
    "111111111111111111111111111111111111111111111111");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("11111111111112111111111111111111111111111111111",
    "11111111111111111111111111111111111111111111111");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("11111111111111111111111111111111111111111111111",
    "11111111111111111111111111111111111111111111111");
    Console.WriteLine(Comparison);
    Comparison = CompareNumbers("1111111111111z111111111111111111111111111111111",
    "11111111111111111111111111111111111111111111111");
    Console.WriteLine(Comparison);
    const string Numbers = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static Int16 GetDigitValue(char Digit)
    Int16 Value = Convert.ToInt16(Numbers.IndexOf(Char.ToUpper(Digit)));
    return Value;
    private static int CompareNumbers(string Number1, string Number2)
    int i = -1;
    Number1 = Number1.TrimStart('0');
    Number2 = Number2.TrimStart('0');
    if (Number1 == Number2)
    return 0;
    if (Number1.Length < Number2.Length)
    return -1;
    if (Number1.Length > Number2.Length)
    return 1;
    do {
    i++;
    } while ((i < Number1.Length) && (GetDigitValue(Number1[i]) == GetDigitValue(Number2[i])));
    if (i < Number1.Length && (GetDigitValue(Number1[i]) <= GetDigitValue(Number2[i])))
    return -1;
    else
    return 1;

  • Use Operator == for String Comparison

    Hi,
    I would like to know more about the impact of using operator == in String Comparison.
    From the reference I get, it state this :
    "Operator (==) compares two object addresses to see whether it refers to the same object."
    I've tested it with 2 codes as below :
    Code 1:
              String Pass1 = "cosmo";
              String Pass2 = "cosmo";          
    if (Pass1==Pass2)
                   System.out.println("1&2:same");
              else
                   System.out.println("1&2:not same");
    Output : 1&2:same
    Code 2:
              String Pass3 = new String("cosmo");
              String Pass4 = new String("cosmo");
              if (Pass3==Pass4)
                   System.out.println("3&4:same");
              else
                   System.out.println("3&4:not same");
    Output : 3&4:not same
    Can anyone kindly explain why is the result so? If operator == compares the addresses, isn't it that the 1st code should also have the output :"1&2:not same".

    Can anyone kindly explain why is the result so?It's an implementation artifact. Strings are pooled internally and because of that any String literal will be represented by exactly one object reference.
    Knowledge of this shouldn't be utilized though. It's safer to follow the basic rule: Use == to compare object references and equals to compare object values, such as String literals.

  • Problems with string comparison using

    I have a problem using the > and < comparison operators.
    When the xsl:if test uses numeric values the comparison works OK. If the
    test uses string values it always returns a false result.
    The style sheet below shows an example (which should run against any
    XML doc with a root element)
    Note - the spurious
    tags are just for debugging- I write the
    output to an HTML page and IE happens to recognise them
    even though the rest of the HTML tags are missing !!
    <?xml version="1.0" ?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:template match="/">
    <xsl:for-each select="*">
    Starting numeric test :
    <xsl:if test="(1 < 2)">
    In Test, ID= <xsl:value-of select="generate-id()"/>
    </xsl:if>
    Finished numeric test :
    Starting alpha test :
    <xsl:if test="('a' < 'b')">
    In Test, ID= <xsl:value-of select="generate-id()"/>
    </xsl:if>
    Finished alpha test :
    </xsl:for-each>
    </xsl:template>
    </xsl:stylesheet>
    null

    Having looked at the XPath spec I believe what I am trying to do (compare strings with gt and lt type tests) is not supported. The spec indicates that they can only be used for node sets or numerics. Presumably the processor is attempting to convert the values to numbers but evaluating them both as NaN (not a number). Can someone confirm this.
    I find this restriction quite strange, is this a situation where an extension function is required ? If so can someone point me to some (Java) examples.
    null

  • Not case sensitive string comparison

    Is there any chance that the coparison function below returns true value?
    Attachments:
    Capture.PNG ‏2 KB

    Please vote for this idea...
    Case Insensitive Comparison Mode for String Equality Comparison
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness

  • Need help for "From concatenate string insert to mysql table"

    Well, most of this problem is a question about SQL syntax. In the VALUES clause you put a comma delimited list of the values to go into the new record. You insert one record at a time. How are the columns defined? Have you done any study on basic SQL?
    Mike...

    i nid to insert values from concatenate string into mysql with using LabSQL, but the result come out from conatenate string is like " 2015-07-08 00:00:00 38.933235E-3" , a logged data of "Date Time Wind Speed(m/s). i nid to put these 3 values into 3 different column in mysql which is Date Time and Wind Speed. How can i pick Date to put inside Date's column, Time into Time's column and Wind Speed into Wind Speed's column in mysql ?
    What i do is
    INSERT INTO wind_speed_data (Date, Time, Wind_Speed) The space in Wind Speed can i put a _ in between Wind Speed? without _ and just put Wind Speed it shows errors.
    VALUES( i have no idea wat to key in at this part ) <--- nid help !
    The Mysql table. Date Time Wind Speed
    The result from concatenate string. Have to insert into mysql.
    My labview program.
    The error i facing.
     

  • String comparisons in TreeMap

    I need to use a concatenation of two Strings as my key in a TreeMap, storing an ArrayList of items associated with the key. Obviously, if the key is found, I simply append to the ArrayList associated with that key. However, whenever I use a concatenation, a new key is always created, even if the two strings creating the concatenation are the same.
    String key = name + storeNum;
    I was under the impression that if I was using Strings, then the TreeMap should use the default compareTo() method which should do a comparison on the String itself, not the memory address, so why would creating the key from a concatenation make any difference? Would creating my own Comparator even help in this situation?

    Hi,
    String object is an immutable. If you concatenat 2 strings you will always receive new String object. In other words you cannot change String, once created it.
    There is mutable "brother" of String - StringBuffer.
    I did not exactly undertand what is your problem, but, hopefully, it helps.

  • Doubt about string comparison

    Hi,
    This may sound the simplest and the most stupid question to most of u reading it. But still share your knowledge.
    Let say we have four Strings defined as
    String s = "something";
    String s1 = "something";
    String t = new String("something");
    String t1 = new String("something");
    now if I compare this strings using '==' operator, This is what happens.
    System.out.println(s==s1); // answer is true
    System.out.println(t==t1); // answer is false
    Why the 1st SOP returns true if java does not treat strings as primitive and creates objects for every string eventhough it is instantiated with literals?

    The answer is:
    Java does a String pooling...
    why it give true, for the first case is
    s == s1
    because all this refers to the value in the String pool.. t and t1 are separate Objects although they have the same value("something"). So... when you do t == t1 you check if t and t1 are refering to the same Object(reference comparison), and since they are referencing 2 distinct Objects, the comparison gives false.
    Cheers !

  • Help me explain this String Comparison Bug!

    <%
          String strGender = rs.getString("gender");
          if(strGender.equals("male"))
               out.println("1");
          if(rs.getString("gender").equals("male"))
                   out.println("2");
          %>In theory, the output should be "12". But guess what, only "2" was printed. I spent hours of debugging because I was supposed to use strGender.equals but the results only ended up in frustrations. So I made experiments, and the direct comparison of rs.getString was the result that worked.
    Can anyone explain to me why?

    You know what is weird...
    the strGender already worked without me changing anything. All i did was eat my dinner, returned after 30mins, then it worked.
    Not the first time I encountered this problem.

  • Record string indicator to mysql database

    Hi experts, i have 3 string indicator and i want to record the data to mysql database. i already have a table with 3 column. how can i do that?
    Thank you
    Attachments:
    test.vi ‏18 KB

    attached is my vi. since i'm really new to programming and labview, can please somebody advise me about my vi. I will use this vi to record minutes of meeting to a mysql database. the dalog_resp.vi is used to fill the responsible string.
    I need to display all mysql data into a table and i need to short the data based on project, meeting date, status and responsbile (i'm thinking to use combo box). e.q if i  choose "SAM" from responsible combo box, i want the table only show the data contain SAM value. And i have another problem...when i put the boolean button into a cluster, it won't call the dialog_resp.vi
    Please advice me...
    Thank you
    Regards
    Ijan
    Attachments:
    db.vi ‏534 KB
    Dialog resp.vi ‏11 KB

  • Problems with string comparison and\or If statement

    Right now I'm trying to make a program that will look into all of my music folders, and rename the .mp3 files to a format i want, based on the id3 tags. The program so far looks in all of the folders I want it to, but I get stuck when I need to check if the files are .mp3 files or not. Here is my code so far:
    package fileRenamer;
    import java.io.File;
    public class FileRenamer {
    public static void main(String[] argv) {
         File artistsFolders = new File("F:/Music (MP3)");
         File[] artists = artistsFolders.listFiles();
         for(int i = 0; i < artists.length; i++){
              if(artists.isFile()) {
                   System.out.println(artists[i].getName());
         } else if (artists[i].isDirectory()) {
              System.out.println(artists[i].getName());
              File albumsFolders = new File("F:/Music (MP3)/"+artists[i].getName());
              File[] albums = albumsFolders.listFiles();
              for(int a = 0; a < albums.length; a++){
                   if(albums[a].isFile()) {
                        System.out.println("-" + albums[a].getName());
                   } else if (albums[a].isDirectory()) {
                        System.out.println("-" + albums[a].getName());
                   File songsFolders = new File("F:/Music (MP3)/"+artists[i].getName()+"/"+albums[a].getName());
                   File[] songs = songsFolders.listFiles();
                   for(int s = 0; s < songs.length; s++){
                        if(songs[s].isFile()) {
                             int dotPos = songs[s].getName().toString().lastIndexOf(".");
                             String extension = songs[s].getName().toString().substring(dotPos);
                             System.out.println(extension);
                             if(extension == ".mp3"){
                                  System.out.println("--" + songs[s].getName());
                   } else if (songs[s].isDirectory()) {
                             System.out.println("--" + songs[s].getName());
    When I test the code, the line System.out.println(extension); prints .mp3 into the console for all of the .mp3 files. Whatever I try, the if(extension == ".mp3") never seems to declare the two equal. If anyone knows what my problem is, I greatly appreciate the advice and help.
    Thanks in Advance,
    James

    Pojo226 wrote:
    I just tried that and it worked perfectly. Thanks.You're welcome.

  • String comparison having single quote

    hi
    i m comparing a string which already have a single quote like this
    var_name=khurram' shehzad
    select * from table where name=' var_name ';
    plz help me how to do it bcoz its creating probelm
    thanks and regards,

    Hi,
    I hope the below example will help you.
    SQL>SELECT 'abc''' FROM DUAL WHERE 'abc''' = 'abc''';
    'ABC
    abc'
    1 row selected.
    SQL>
    Regards

Maybe you are looking for