0

I want to replace the LIMIT quantity in a mySQL query to a variable.

This does work:

$x = $conectarDB->prepare("
  SELECT contenidoID, titulo, fecha, encabezado
  FROM contenidos
  WHERE publicado = 1
  ORDER BY fecha DESC
  LIMIT ".$limit."
  ");
$x->execute();
$y = $x->fetchAll(PDO::FETCH_ASSOC);

But this doesn't:

$x = $conectarDB->prepare("
  SELECT contenidoID, titulo, fecha, encabezado
  FROM contenidos
  WHERE publicado = 1
  ORDER BY fecha DESC
  LIMIT ?
  ");
$x->bindParam(1, $limit);
$x->execute();
$y = $x->fetchAll(PDO::FETCH_ASSOC);

I receive this error:

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2'' at line 5' in /public_html/includes/footer-info-extra.php:25

How to change that number in a secure way? What am I doing wrong?

Thanks for your help!

Please note that I've been reading about how to do that in MySQL, I want to do it in php

Rosamunda
  • 14,620
  • 10
  • 40
  • 70
  • Just look up how bind_param actually works. http://php.net/manual/de/mysqli-stmt.bind-param.php – infinitezero Apr 16 '18 at 16:40
  • You are using PDO it's slightly different then Mysqli. In PDO there are few ways to achieve the same results. you can first try: $x = $conectarDB->prepare(" SELECT contenidoID, titulo, fecha, encabezado FROM contenidos WHERE publicado = 1 ORDER BY fecha DESC LIMIT :limit "); $x->execute([ 'limit' => $limit ]); $y = $x->fetchAll(PDO::FETCH_ASSOC); This code works on my old projects. You can also look on PHP.net Reference: http://php.net/manual/de/pdostatement.bindparam.php – Eden Reich Apr 16 '18 at 16:55

0 Answers0