anagram finder program php mysql

i am trying to write a program for anagram finder in php mysql.. i have dictionary in database which has only one field named 'word' and it contains 500000 rows.

by using php i tried to pull words one by one from database.. After getting a word i created 2 for loops which performs character by character comparison..

for example.. let the input word be 'abcdef'..

consider i am fetching the word 'fade' from database..

i am writing a loop and checking whether the word fade is in abcdef .. if yes i am printing the word.. if not, i will fetch next word from database..

i wrote the code.. but i am getting an empty page as output.. pls help..

i have one more question. is there any other way to find the substring of a word without using character by character comparison?

for example : if my input is fedcba.. i sort it as abcdef.. and dictionary word is fade and i sort it as adef.. is thr any function to find whether adef is a substring of abcdef..

Forget checking each word in PHP. That's a CPU nightmare!

Add a second column to your table, and have the word spelled out in alphabetical order. For example:

Word : AlphaWord
Test : estt

Then you can simple run a query like this:

select word from table 1 where AlphaWord = (select AlphaWord from table1 where word='$yourWord') order by word asc;

Edit: If you didn't want to match words within other words, you could pop a Fulltext search index on the AlphaWord column and then use the Match()... against() syntax which will return the matches very fast. However, as this operator would only allow for a wildcard to be placed on the end of a search string, it won't match machete->aceehmt with ache->aceh. Having said that, to be honest, you couldn't really add in a wildcard in a normal search either that would match them.

You will have to write your own user define function to get sorted string of letters:

CREATE FUNCTION fn_sort_string(arg_word VARCHAR(255)) RETURNS VARCHAR(255)
BEGIN
    DROP TEMPORARY TABLE IF EXISTS temp;
    CREATE TEMPORARY TABLE temp(letter CHAR(1));

    SET @var_counter = 0;
    SET @var_len = LENGTH(arg_word);

    WHILE(@var_counter < @var_len)
    DO
        INSERT INTO temp VALUES (SUBSTRING(arg_word, @var_counter, 1));
        SET @var_counter = @var_counter + 1;
    END WHILE;

    SELECT GROUP_CONCAT(DISTINCT letter ORDER BY letter SEPARATOR '')
    INTO @var_sort_word
    FROM temp;

    DROP TEMPORARY TABLE IF EXISTS temp;

    RETURN IFNULL(@var_sort_word, "");
END;

Following query will find sorted input word in sorted dictionary word:

SELECT * 
FROM dictionary 
WHERE fn_sort_string(input_word) LIKE CONCAT('%',fn_sort_string(word),'%');