PHP/MySQL - 如果使用变量而不是硬编码值,查询将失败
我搜索了又搜索并尝试了我读过的内容,但由于某种原因,当使用变量而不是硬编码值时,我的查询失败了。
这是我的查询:
$bugzilla_query="SELECT * FROM profiles WHERE userid='".$bugzilla_id."'";
我通过执行以下操作来获取 cookie 的值:
$bugzilla_id = $_COOKIE["Bugzilla_login"];
我开始怀疑查询是错误的,但保存 cookie 值的变量没有正确检索它,即使它看起来是正确的,但如果我再一次设置 $bugzilla_id = 642;
它仍然不起作用,但如果我这样做 $bugzilla_query="SELECT * FROMprofiles WHERE userid=642";
它就完美了。
嗯,一头雾水!
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 $bugzilla_query="SELECT * FROM profiles WHERE userid=642";
it works perfectly.
Hmm, confused!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,您永远不想将用户可以直接修改的任何值放入查询中。此外,如果这应该是一个数字,那么为什么在启用变量的查询中将其放在单引号中,而不是在硬编码的查询中?注意到区别了吗?试试这个:
这将确保在进入查询之前将其转换为整数。
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:
That'll make sure it's cast as an integer before going into your query.
如果 $bugzilla_id 应该是一个整数,请尝试将其包装在 intval() 中以确保它作为整数传递。
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.
非常感谢您的帮助。事实证明,这是我在代码中犯的一个愚蠢的拼写错误:
我有:
当我显然需要时:
我将
$bugzilla_id
设置为''
因为我错过了=
进行比较检查。我对此的建议 - 我可能会自己开始这样做 - 是将变量放在右侧,因此以相反的方式编写比较,然后它会立即失败。巧合的是,我在 Joel 自己的网站上读到,他认为这是优秀程序员的标志:/
Thanks very much for all your help. Turns out it was a stupid typo I made in my code:
I had:
When I obviously needed:
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 :/