A
A
Albert Kazan2018-03-10 15:37:52
PHP
Albert Kazan, 2018-03-10 15:37:52

Why doesn't LIMIT work in this prepared query?

$sql = "SELECT t1.target_id, SUM(t1.cnt) as hm, t2.id, t2.name, t2.second_name, t2.avatar, t2.studyGroup FROM votes AS t1, people AS t2 WHERE t1.target_id=t2.id GROUP BY t2.id ORDER BY hm DESC, t2.name ASC LIMIT ?";
  $o1 = $this->DB->prepare($sql);
  $args = array(
    $this->rl_count
  );
  $o1->execute($args);

Outputs nothing. If you just put a number, then it displays records, but not with a prepared expression. $this->rl_countit's 20.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2018-03-10
@Farrien

limit can be passed as a parameter. The problem is a combination of two facts:
1) prepared statements emulation in pdo passes strings by default
2) the mysql parser states that limit must be a number
Therefore, one of these nuances needs to be corrected:
1) specify the parameter type explicitly:

$q = $dbh->prepare("select ... limit :limit");
$q->bindValue(':limit', 10, PDO::PARAM_INT);
$q->execute();

2) either disable prepared statements emulation: PDO::ATTR_EMULATE_PREPARES => false in the connection settings.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question