如何根据匹配的用户输入在 PHP 和 return 结果中查询数据库?

How do I query a database in PHP and return results based on matching user-input?

我正在尝试使用 MySQLi 编写一个 PHP 脚本来查询数据库。

如果可以对照数据库检查用户输入,然后 return 如果 [=37] 的 'root' 列中的字符串来自 'conjugation' 列,我会喜欢=] 'normal_verbs' 在输入中。

所以如果用户输入类似于 "foobar",并且根列有 "foo",我希望它在 'foobar' 中看到 'foo' 并且return 该行中 'conjugation' 的值。

我似乎无法让查询按我希望的方式工作。我在下面使用的基本上只是一个占位符。我不完全明白为什么它不起作用。

我正在尝试的是:

        function db_connect() {

            static $connection;

            if(!isset($connection)) {
                $connection = mysqli_connect('localhost','user','password','Verb_Bank');
            }

            if($connection === false) {
                return mysqli_connect_error(); 
            }
            return $connection;
        }

        function db_query($query) {
            $connection = db_connect();
            $result = mysqli_query($connection,$query);

            return $result;
        } 

        function db_quote($value) {
                $connection = db_connect();
                return "'" . mysqli_real_escape_string($connection,$value) . "'";
            }    
$m= db_query("SELECT `conjugation` from normal_verbs where `root` in (" . $y . ")");
    if($m === false) {
        // Handle failure - log the error, notify administrator, etc.
    } else {
        // Fetch all the rows in an array
        $rows = array();
        while ($row = mysqli_fetch_assoc($m)) {
            $rows[] = $row;
        }
    }
    print_r ($rows);

它没有给我任何错误,所以我认为它正在连接到数据库。

EDIT2:我错了。由于误解 MySQLi,我遗漏了一些明显的东西,并相应地编辑了代码。所以上面的代码确实有效,因为它连接到数据库并且 returns 结果,但我仍然难以理解一个可行的 SQL 语句来做我想做的事情。

请试试这个:

SELECT 'conjugation' FROM 'normal_verbs' WHERE " . $y . " LIKE CONCAT('%',root,'%')

它选择根目录中任何位置包含 $y 的所有行。

此外,您的代码容易受到 SQL 注入攻击。请查看 here 了解更多信息。

试试这个SQL这样查询

SELECT `conjugation` from normal_verbs where `root` like '%$y%'