0

My question is simple but i didn't find any question or answer for this.I mean they are not solution for my case. Here is the my code.

$characters = $_GET["search"];
$characters2 = "%". $characters . "%" ;
$statement = $connection->prepare(
    "SELECT name,username FROM users WHERE 'name' LIKE :username or 'username' LIKE :username");
$statement->bindParam(':username', $characters2, PDO::PARAM_STR);
$statement->execute();

Problem is if you have david in the name column in the database and your $_GET["search"] is "davi" or "david" it couldn't find the david's row.

Returns empty.

M. Witney
  • 45
  • 3
  • 12
  • I don't think you need 'name' quoted. I could be wrong though. I feel like it is just comparing 'name' and 'david' – DJSweetness Aug 29 '17 at 19:58
  • @DJSweetness you are not wrong, and as written it's nonsense which is why OP thinks it's working incorrectly. OP, use backticks (not single quotes) around your field names and use single quotes around your search terms: `WHERE name LIKE ':username' or username LIKE ':username'` – JNevill Aug 29 '17 at 19:59
  • @JNevill according to this resource http://php.net/manual/tr/pdostatement.bindparam.php#99698 your "use single quotes around your search terms" is wrong.But i musn't use single quotes around my field names. – M. Witney Aug 29 '17 at 20:18
  • Oh yes. That makes sense with bindParam. Sorry for the misleading info. – JNevill Aug 29 '17 at 21:15

1 Answers1

0

You're comparing the string 'name' and the input by the user 'david'. With sql, all you need to put is the name of the column, which in your case would be just name. Same thing for username

Thus,

$statement = $connection->prepare(
"SELECT name,username FROM users WHERE name LIKE :username or username LIKE :username");

WITHOUT the quotes around name and username will work

DJSweetness
  • 153
  • 1
  • 14