5

PDO seems to add quotes to the bound parameters automatically in a prepared sql statement.

I do not want this functionality when I am trying to limit the number of results because this should be seen as an integer to mysql.

function fixStatistics($metal, $currency, $months){
$db = connectPDO();
$sql = '
        SELECT [COLUMN NAMES]
        FROM [TABLE NAMES]
        WHERE [WHERE STUFF]
        GROUP BY `Month`
        ORDER BY MONTH(DateStamp) LIMIT :numMonths
';

$stmt = $db->prepare($sql);
$stmt->execute(
        array(
        ':metal' => $metal,
        ':currency' => $currency,
        ':numMonths' => $months // Problem Code
    )
);
$statistics = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $statistics;
}

I can resolve this issue by manually injecting / concatenating the sql statement - Not what I want to do.

ORDER BY MONTH(DateStamp) LIMIT ' . $numMonths

But is there a way of casting the :numMonths directly to an int at the point of $stmt->execute();?

Gravy
  • 12,264
  • 26
  • 124
  • 193

1 Answers1

6

from the docs about the execute array param:

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

use something like this before execute:

$stmt->bindValue(':numMonths', intval($months), PDO::PARAM_INT);
x4rf41
  • 5,184
  • 2
  • 22
  • 33
  • please don't answer exact duplicates in the duplicate. add the answer to the existing question if you feel it is missing. – hakre Jun 25 '13 at 11:52
  • Marking as a duplicate earns one no reputation points. – Your Common Sense Jun 25 '13 at 12:08
  • 1
    @hakre - this question ranks higher than the original question for some Google queries. If duplicates are not to be deleted on SO, surely they should be answered? – colincameron Feb 11 '15 at 12:49
  • @c.cam108 no, they should not. Answering them prevents from a (quicker) delete. – hakre Feb 11 '15 at 13:25
  • This is a solution, but what's strange to me is that PHP.net documentation shows an example using an int like this without problems: $calories = 150; $sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?'); $sth->execute(array($calories, $colour)); Maybe it works because of the comparison working with strings too. – foxesque Nov 22 '22 at 11:09