tony_perkis666
tony_perkis666

Reputation: 251

Loop MySQL column values as variable

The following code is intended to use levenshtein() to compare a user-input word to the values in a column of a MySQL table:

    $searched=$_POST['searched'];

$sql = "SELECT * FROM `word_list`;";

$result = mysqli_query($conn,$sql);

while($row=mysqli_fetch_assoc($result))
    $title = $row['word'];
    $sound = levenshtein($searched, $title);
    if ($sound < 4) {
    echo $title;
}

?>

My confusion stems from the mechanics of actually looping in the values of the "word" column of the table as a variable for the second string int he levenshtein function.

Ultimately, I'd like to loop the values from that column into the $title variable, and echo the values that produce a levenshtein distance less than 4, but I cannot seem to return any output.

Upvotes: 0

Views: 327

Answers (1)

hek2mgl
hek2mgl

Reputation: 157947

Using a while loop is correct in your example. But you are mixing the mysql and the mysqli extension:

$result = mysqli_query($conn,$sql);
...
while($row=mysql_fetch_assoc($result))

You'll have to use mysqli_fetch_assoc() instead.


Also you are missing a closing } at the end of the while loop. The complete example should look like this:

$searched = $_POST['searched'];
$sql = "SELECT * FROM `word_list`;";
$result = mysqli_query($conn, $sql);

while($row = mysqli_fetch_assoc($result))
    $title = $row['word'];
    $sound = levenshtein($searched, $title);
    if ($sound < 4) {
        echo $title;
    }
}

Upvotes: 1

Related Questions