开发者

PHP/MySQL - query fails if a variable is used instead of a hard coded value

I've searched and searched and tried the things I've read but for some reason my query fails when using a variable rather than a hardcoded value.

This is my query:

$bugzilla_query="SELECT * FROM profiles WHERE userid='".$bugzilla_id."'";

I am getting the value of the cookie by doing the following:

$bugzilla_id = $_COOKIE["Bugzilla_login"];

I am starting to doubt that the query is wrong but the variable holding the cookie value is not retrieving it correctly even though it looks correct but then again if I set $bugzilla_id = 642; it still doesn't work but if I do 开发者_StackOverflow中文版$bugzilla_query="SELECT * FROM profiles WHERE userid=642"; it works perfectly.

Hmm, confused!


You never want to put any value that could be modified by a user directly into a query, in general. Additionally if that's supposed to be a number, why are you putting it in single quotes in your variable enabled query, but not in your hard coded one? Notice the difference? Try this:

$bugzilla_query = sprintf("SELECT * FROM profiles WHERE userid = %d", $bugzilla_id);

That'll make sure it's cast as an integer before going into your query.


If $bugzilla_id is supposed to be an integer, try wrapping it in an intval() to make sure it's being passed as an integer.


Thanks very much for all your help. Turns out it was a stupid typo I made in my code:

I had:

if ($bugzilla_id <= 0 || $bugzilla_id = '' || !isset($bugzilla_id))
{
     return "No Bugzilla cookie is set!";
}    

When I obviously needed:

if ($bugzilla_id <= 0 || $bugzilla_id == '' || !isset($bugzilla_id))
{
    return "No Bugzilla cookie is set!";
}    

I was setting $bugzilla_id to '' because I missed an = in the comparison checking.

My advice for that - and I may start doing this myself - would be to put the variable on the right hand side, so write your comparisons the opposite way round, then it will fail straight away. Coincidentally, I read on Joel's own website that he sees this as a sign of a good programmer :/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜