Search code examples
phpmysqlpdobindparam

Query does not work as expected with bindParam but it does with raw input?


I have a query that should show all content from a specific date, like "show me all articles from 01-01-2020 to now".

The date is in unix. And I'm using PHP 7.2.

If I use bindParam instead of the real number, it shows content from within that date and older as well.

If I just type the number (the unix date), it shows the content ok, meaning that the content is all within the date range.

HERE'S MY QUERY:

  $y = $conectarDB->prepare("
      SELECT DISTINCT SQL_CACHE
      contenidos.contenidoID AS contID, 
      titulo, 
      fecha, 
      tipoContenidoID
      WHERE fecha > ?
      ORDER BY contenidoID DESC
  ");
  $y->bindParam(1, $fecha);
  $y->execute();
  $resultado = $y->fetchAll(PDO::FETCH_ASSOC);

Tying to sort it, I forced the date ($fecha variable) to be an integer, just in case the problem was that it was being interpreted as a string:

$fecha = (int)$fecha;

MySQL nor PHP show any errors, and the query gets excecuted, but showing older results as well, not following the range.


Solution

  • Just in case it helps someone in the future...

    The problem was that the database field was a char type, instead of an integer.

    So even with explicit declaration in PHP, MySQL kept considering it's contents as a string.

    It was being read as:

      $y = $conectarDB->prepare("
          SELECT DISTINCT SQL_CACHE
          contenidos.contenidoID AS contID, 
          titulo, 
          fecha, 
          tipoContenidoID
          WHERE fecha > '1577847600'
          ORDER BY contenidoID DESC
      ");
    

    Instead of:

      $y = $conectarDB->prepare("
          SELECT DISTINCT SQL_CACHE
          contenidos.contenidoID AS contID, 
          titulo, 
          fecha, 
          tipoContenidoID
          WHERE fecha > 1577847600
          ORDER BY contenidoID DESC
      ");
    

    So, instead of just using:

      $y->bindParam(1, $fecha);
    

    I've changed it to:

      $y->bindParam(1, $fecha, PDO::PARAM_INT);
    

    To make MySQL understand that it is indeed an integer.