Search code examples
phphtmlmysqlphpmyadmincodeigniter-2

searching needle when we know the haystack in sql


I have a database of many country codes with their corresponding country names for example:

mauritius   230
canada      1
testcountry 1234

each country may have between 1 to 5 starting number. The user will enter any phone number for example 23012345678 and the output should be mauritius.

How can I perform such sql lookup in the database? I was thinking that I could make 5 substring of the input data:

2
23
230
2301
23012

and find a match, however this is not efficient. Any idea how to proceed? (php)


Solution

  • You can use a like query by matching your code column with phone number by using a wild card after column so it will match only starting characters

    select *
    from countries
    where '23012345678' like concat(`code`,'%') > 0
    

    DEMO

    Edit from comments

    You can use length() function on your code column and order results with highest length for most matched country code

    select *
    from countries
    where '23012345678' like concat(`code`,'%') > 0
    order by length(`code`) desc 
    limit 1
    

    DEMO 2