Sourav Chatterjee
Sourav Chatterjee

Reputation: 67

Why is SQL query returning 0? What will be the actual query?

require 'connect_db.php';
require 'User.php';
$stmnt = $con->prepare("select f_name, l_name from user where f_name LIKE :q OR l_name LIKE :q OR dept LIKE :q OR batch LIKE :q OR email LIKE :q");
$q = $_GET['q'];
$q1 = "'%".$q."%'";
$stmnt->bindParam(':q',$q1);
$stmnt->execute();
$results = $stmnt->fetchAll(PDO::FETCH_OBJ);
echo count($results);

When I am writing it mysql command line it is returning 1 row but this code is not.. please help me to correct it.

My sql query is :select f_name, l_name from user where f_name LIKE '%s%' or l_name LIKE '%s';

this is returning 1 row.

Upvotes: 0

Views: 186

Answers (2)

Ravi Hirani
Ravi Hirani

Reputation: 6539

Try this way. You can do the same without using concatenation operator (.)

Use double quotes with curly bracket and put variable inside it.

$q1 = "%{$q}%";

OR directly write

$q1 = "%{$_GET['q']}%";

Upvotes: 0

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31143

When you use parameters they will be sent as is and escaped when needed. You write

$q1 = "'%".$q."%'";

This means that the string in the end will be '%something%' and this will be escaped into the SQL query. You most likely don't want to find strings beginning and ending with ' so remove them to get %something%.

$q1 = "%".$q."%";

Upvotes: 3

Related Questions