0

This is my code

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

it does not retun the exact result I need exact ( What is Your Name ) will some body help me to do this.

Thanks in Advance !

Sajid Mehmood
  • 483
  • 2
  • 6
  • 18

4 Answers4

1

Try adding '%' before and after your variable as shown below.

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

EDIT To prevent SQL injection just do this:

$question = mysql_real_escape_string($question);
Bhawesh Chandola
  • 511
  • 5
  • 19
1
 $question = rtrim(ltrim(strip_tags(What is your Name)));
$query = "SELECT * FROM `def_questions` where `question` LIKE '%$question%' ";
Sajid Mehmood
  • 483
  • 2
  • 6
  • 18
1

Your code may be vulnerable for SQL Injection. You should use prepared statements for passing values to query:

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

Note that you should also escape some special characters from searched value, to make it work correctly with LIKE operator (for example treat % as % instead of "anything", see How to use a percent (%) in a LIKE without it being treated as a wildcard?):

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

The easiest way to do the whole thing is probably by using Query:

$questions = (new \yii\db\Query())
    ->from('def_questions')
    ->where(['like', 'question', $question])
    ->all();

Query will do escaping for you and will return results for SQL query:

SELECT * FROM `def_questions` where `question` LIKE '%What is your Name%'
rob006
  • 21,383
  • 5
  • 53
  • 74
0

If You want exact result, you can use = instead of LIKE

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