0

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>";

}
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Tonald Drump
  • 1,227
  • 1
  • 19
  • 32

2 Answers2

1

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.

chris85
  • 23,846
  • 7
  • 34
  • 51
0

How about this ?

<?php 

$search = "Paul"; // The string I want compared to each DB entry
$query = "SELECT name, levenshtein(name, '".mysqli_real_escape_string ($dbc, $search)."') AS result FROM names";

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

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

  echo "Levenshtein Ratio for ".$row['name'].' : '.$row['result']."<br />";

}
Nounours
  • 56
  • 5