-4

So, I'd like to use the LIKE operator in a SQL query with a php variable. Basically I need to check if 'serie_nb' begins with the number contained by the variable $bloc.

Here is my code:

public function getSeriesCount($bloc){
    $like = (String)$bloc . '_';
    $query = 'SELECT COUNT(*) AS countSeries FROM projet_web.series WHERE serie_nb LIKE ' . $like;
    $result = $this->_db->query($query);
    $countSeries = 0;
    if ($result->rowcount() != 0){
        $countSeries = $result->fetch();
    }
    return $countSeries;

}

And here is the error I get (which is caught when the query is executed):

Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '2_' in 'where clause'

I don't really see why I get that error...

Thanks for the help !

Aldwoni
  • 1,168
  • 10
  • 24
TheSonNel
  • 21
  • 5
  • 3
    You really should be using prepared statements – Masivuye Cokile May 04 '17 at 13:41
  • 2
    ...and looking for all of the duplicates on SO before posting a question – mickmackusa May 04 '17 at 13:41
  • 3
    see [When to use single quotes, double quotes, and backticks in MySQL](http://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql) – Masivuye Cokile May 04 '17 at 13:42
  • Virtually any SO `LIKE` question would have cleared this up for you: http://stackoverflow.com/questions/tagged/sql-like+php – mickmackusa May 04 '17 at 13:44
  • Possible duplicate of [When to use single quotes, double quotes, and backticks in MySQL](http://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql) – Tom Regner May 04 '17 at 14:21

1 Answers1

1

The issue with your statement is the use of quotes, you need to view this so question on how to use the quotes : When to use single quotes, double quotes, and backticks in MySQL

the value in the $like within the where clause is read as a colomn name because you did not wrap your $link string in quotes.

The best and simple straight forward solution is to use prepared statements,

public function getSeriesCount($bloc)
{
    $like = (String)$bloc . '_';
    $query = 'SELECT COUNT(*) AS countSeries FROM projet_web.series WHERE serie_nb LIKE  ? ';
    $stmt  = $this->_db->prepare($query);
    $stmt->execute([$like]);

    $countSeries = $stmt->fetchall();

    if (count($countSeries) > 0) {

        return $countSeries;
    }


}
?>
Community
  • 1
  • 1
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34