如何从mysql数据库中搜索整个句子?

64jmpszr  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(321)

这是我的密码

$question = "What is your Name";
    $query = "SELECT * FROM `def_questions` where `question` LIKE '$question' ";

它没有返回确切的结果,我需要确切的(你叫什么名字)会有人帮我做这件事。
提前谢谢!

8aqjt8rx

8aqjt8rx1#

尝试在变量前后添加“%”,如下所示。

$question = "What is your Name";
$query = "SELECT * FROM `def_questions` where `question` LIKE '%$question%' ";

编辑以防止sql注入只需执行以下操作:

$question = mysql_real_escape_string($question);
fcy6dtqo

fcy6dtqo2#

如果想要得到精确的结果,可以使用=而不是like

$question = "What is your Name";
$query = "SELECT * FROM `def_questions` where `question` = '$question'"
g52tjvyc

g52tjvyc3#

$question = rtrim(ltrim(strip_tags(What is your Name)));
$query = "SELECT * FROM `def_questions` where `question` LIKE '%$question%' ";
vjhs03f7

vjhs03f74#

您的代码可能易受sql注入攻击。您应该使用准备好的语句来传递要查询的值:

$questions = Yii::$app->db
    ->createCommand("SELECT * FROM `def_questions` where `question` LIKE :question", [
        ':question' => "%$question%",
    ])
    ->queryAll();

请注意,您还应该从搜索值中转义一些特殊字符,以使其能够正确使用 LIKE 运算符(例如) % 作为 % 请参阅如何在like中使用百分比(%)而不将其视为通配符?),而不是“anything”:

$question = strtr($question, [
    '%' => '\%',
    '_' => '\_',
    '\\' => '\\\\',
]);
$questions = Yii::$app->db
    ->createCommand("SELECT * FROM `def_questions` where `question` LIKE :question", [
        ':question' => "%$question%",
    ])
    ->queryAll();

最简单的方法是使用 Query :

$questions = (new \yii\db\Query())
    ->from('def_questions')
    ->where(['like', 'question', $question])
    ->all();
``` `Query` 将为您执行转义并返回sql查询的结果:

SELECT * FROM def_questions where question LIKE '%What is your Name%'

相关问题