2

I'm having a problem where PDO encapsulates int values using quotes and subsequently makes queries fail.

This is the code (using a wrapper function)

$newest = query("SELECT id, body, upvotes, downvotes 
                FROM suggestions ORDER BY timestamp DESC LIMIT :min, :max",
    array(
        ':min' => $min,
        ':max' => $max
    )
);

And this is the resulting bad query which causes an error (notice the quotes around the LIMIT values)

SELECT id, body, upvotes, downvotes FROM suggestions ORDER BY timestamp DESC LIMIT '0' , '50'

I'm passing an array of values:

array(
    ':min' => $min,
    ':max' => $max
)

They're both INTs, and from what I read on the internet PDO should automatically find that out and use PDO::PARAM_INT when binding them. The problem is it doesn't actually do that, and since my only way to pass them is through an array I'd like to ask if there's a way to force them to be PDO::PARAM_INT without having to use bindParam().

Thanks in advance.

5
  • also why your only way is with array? Commented Jul 6, 2011 at 15:14
  • It's because I'm using a wrapper function, and that wrapper function only allows arrays Commented Jul 6, 2011 at 15:16
  • is there a problem for you if you use only for this time standard PDO class? (tho it's not the best idea) Commented Jul 6, 2011 at 15:16
  • I don't want to clutter up the code if there's a better solution. Commented Jul 6, 2011 at 15:17
  • Are $min and $max explicitly set to integers in PHP or not? Commented Jul 6, 2011 at 15:20

1 Answer 1

1

If you use a wrapper and you cannot use bindParam then you can do :

$min=(int)$min;
$max=(int)$max;
query("SELECT id, body, upvotes, downvotes 
                FROM suggestions ORDER BY timestamp DESC LIMIT $min, $max");

This is not the best idea. If you want to keep standards you should improve your wrapper to handle such cases.

Like add a 3rd param in your wrapper

function query($q,$paramArray,$bindParamArray) {}

So you can effectively use bindParam too

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it fixed the error but, now the query returns an empty result. This is strange because executing the same query from PHPMyAdmin gives a valid (not empty result). Is there a way to see the query that ended up being executed using PDO?
Nevermind! It was just a small problem on my side. Replacing the values directly into the string worked fine. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.