Search code examples
phpmysqlfunctionmysqlilevenshtein-distance

Return result of an mysql function


I have installed this Levenshtein function in MYSQL. The maker advises to use this:

select levenshtein('butt', 'but') from test;
select levenshtein_ratio('butt', 'but') from test;

I want to calculate the Levenshtein Ratio between $search and each "name" entry in the DB and then echo it in PHP.

How can I accomplish that? Thanks in advance

$search = "Paul"; // The string I want compared to each DB entry

$query = "SELECT name, ??? FROM names"; // What's the MYSQL I need to use?

$response = @mysqli_query($dbc, $query);

while($row = mysqli_fetch_array($response)){

  echo "Levenshtein Ratio: ".$row['???'];
  echo "<br>";

}

Solution

  • You need to use an alias the function return

    SELECT levenshtein('butt', 'but') as levenshtein FROM 
    

    then it can be accessed from the levenshtein index.

    $row['levenshtein']
    

    Also note:

    In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

    So if you didn't want the alias you could do:

    $row[1]
    

    this is less readable/maintainable to me though.

    When in doubt about what an array contains you can check it with print_r or var_dump. Those will give you the indices and the values the array has.