Php-根据搜索表单在数据库中搜索输入的最后两个字符


Php - Search last two characters of input in database based on search form

我在php中有一个搜索页面,并且我已经在数据库中存储了许多术语。假设我输入

Helloworld

在搜索表上。我想找到最后一个

2 characters (Ld)  in the database table.

我已经尝试过mb_functions和其他替代方案,但都没有成功。我受够了。

我不知道你到底需要什么,但这将搜索字符串的最后2个字符,在表中找到与之匹配的列值,然后回显它。还要检查字符串是否长于2。

$string = 'helloworld';
$newstring = substr($string, -2);
// Connect to database
try {
    $db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'root', 'password123');
} catch (PDOException $e) {
    echo $e->getMessage()."<br>";
    die();
}
// Search for the $newstring in a table
$sql = $db->prepare("SELECT * FROM table_name WHERE column = :newstring");
$query = $sql->execute(array(
    ":newstring" => $newstring
    )
);
foreach ($sql as $row) {
    $dbstring = $row['column_name'];
    echo $dbstring . '<br>';
}