-1

I'm having some trouble using a php variable with an SQL LIKE command. The code below acts as it should. However, if I change $model = "Cruze Limited"; I don't get any returns from the database. I'm expecting at the very least the same result I'm getting when $model = "Cruze"; which returns all vehicles that's model contains "Cruze".

I have a feeling I'm just missing some small syntax error but I can't place my finger on it. I apologize in advance if that's the case.

<?php 
$make = "Chevrolet";
$model = "Cruze";

$trim = "LT";

$year = '2017';

$query = "SELECT *
          FROM my_table
          WHERE year = '$year'
          AND make = '$make'
          AND model LIKE '$model%'";

$statement = $db->prepare($query);
$statement->execute();

<

html>
<body>
  <?php while($vehicles = $statement->fetch()): ?>
      <h4><?= $vehicles['year'] ?></h4>
      <h4><?= $vehicles['stock'] ?></h4>
      <h4><?= $vehicles['kms'] ?></h4>
      <h4>$<?= $vehicles['price'] ?></h4>
      <h4><?= $vehicles['make'] ?></h4>
      <h4><?= $vehicles['model'] ?></h4>
      <a href="<?=$vehicles['photos']?>">Photo</a>
  <?php endwhile ?>
<body>
</html>



?>
Brendan
  • 3
  • 5
  • 1
    " I'm expecting at the very least the same result I'm getting when `$model = "Cruze";`" - Well it's not the same. – Paul Spiegel Mar 15 '18 at 20:18
  • 1
    `$model%` returns all records that **begins** by `$model`, not "contains". – Syscall Mar 15 '18 at 20:18
  • A good way to check this is to output the query in some way. Right after the body tag add `= $query; ?>` and that should at least point you in the right direction. Also, @Syscall is correct, you should use `'%$model%'` instead of `'$model%'` – mtr.web Mar 15 '18 at 20:21

1 Answers1

-1

Try this

$query = "SELECT *
          FROM my_table
          WHERE year = '$year'
          AND make = '$make'
          AND LOCATE(model,'$model') > 0";
masatar
  • 88
  • 6