-1

i just want a direct answer and explanation why my prior query works but the latter does not..

here is the query that works just fine:

$sql = "SELECT * FROM productslist WHERE brand LIKE ?";

and this doesn't work at all and just returns an error:

$sql = 'SELECT * FROM productslist WHERE brand LIKE "%'.$search_string.'%"';

can someone please explain me why the latter query doesn;t work at all?

thanks in advance..

makLoy
  • 23
  • 5
  • 1
    What is the value of `$search_string` ? Are you using prepared statements ? – Madhur Bhaiya Sep 13 '18 at 10:03
  • 1
    any error? what value is assigned to search_string variable? – st4hoo Sep 13 '18 at 10:03
  • Are you aware of sql injection https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – karen Sep 13 '18 at 10:04
  • Try to change quotas you use like this: $sql = "SELECT * FROM productslist WHERE brand LIKE '%" .$search_string. "%' "; Sometimes quotas cause errors. In alternative you can always echo your query, copy it and execute directly in db and see if you have any db error. – Sigma Sep 13 '18 at 10:09
  • My guess is that `$search_string` contains a quote symbol. – Nick Sep 13 '18 at 10:11
  • @Nick i think your suggestion about testing a query is a good way of testing if a query can be successfully executed.. – makLoy Sep 13 '18 at 10:50
  • which api did you use to connect with here and query? mysql_? mysqli_? PDO? other? – Funk Forty Niner Sep 13 '18 at 12:03

2 Answers2

0

I tested the query with a table on my own DB. worked fine... I used a constant

Try mysqli_real_escape_string:

$search_string = mysqli_real_escape_string($conn, $search_string);
    $sql = 'SELECT * FROM productslist WHERE brand LIKE "%'. $search_string  .'%"';
Guy Louzon
  • 1,175
  • 9
  • 19
-1

Try this with PDO (Edit: Including PDO connection string since he didn't specify if he was using PDO) -

$dbh = new PDO("mysql:hostname=$your_server;dbname=$database_name, $username, $password);

$sql = "SELECT * FROM productslist WHERE brand LIKE :search";
$query = $dbh->prepare($sql);
$query->bindValue(":search", "%$search_string%");
$query->execute();

$result = $query->fetchAll(PDO::FETCH_ASSOC);
iamgory
  • 862
  • 1
  • 6
  • 10