Search code examples
phpmysqlpdosql-like

SQL SELECT WHERE field LIKE PHP variable.


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>



?>

Solution

  • Try this

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