在 PHP/MySQL 中比较变量字符串相等性的最佳方法是什么?
我正在尝试检查通过 URL 传递的字符串,并从 MySQL 数据库中获取该字符串匹配的所有结果。
我根据输入发送不同的查询,但有问题的查询基本上是这样的(它确实更长):
if ($projectsname) {$result = mysql_query("SELECT item FROM items WHERE projectname=$projectsname",$db)}
问题是 $projectsname 是一个字符串。我的所有其他查询都返回一个整数并且工作正常。但在这种情况下,除非我将其放在引号中,否则我无法让它在实际的 PHP 代码中给出正确的结果,这就是我的做法:
$projectsname = (isset($_GET['projectname']) && !empty($_GET['projectname'])) ? '"'. $_GET['projectname'] .'"' : 0;
...通过将引号附加到创建变量的数据中。那行得通。对我来说这似乎是错误的。
有没有更好的方法来进行这种比较?
(我希望我可以说这是一个新手问题,但这是我作为一名尝试编码的设计师多年来经常遇到的问题。)
如果您知道比我在这里使用的术语更好的术语,请随意编辑问题(并让我知道您的编辑内容 - 我很难表达这个问题。)。
I'm trying to check a string passed through the URL and get back all results from a MySQL database where that string is a match.
I send different queries based on the input, but the one in question looks basically like this (it's really much longer):
if ($projectsname) {$result = mysql_query("SELECT item FROM items WHERE projectname=$projectsname",$db)}
The issue is that $projectsname is a string. All my other queries return an integer and work fine. But in this case I can't get it to give me a proper result in the actual PHP code unless I put it in quotes, and here's how I did that:
$projectsname = (isset($_GET['projectname']) && !empty($_GET['projectname'])) ? '"'. $_GET['projectname'] .'"' : 0;
...by appending the quotes to the data that creates the variable. And that works. It just seems wrong to me.
Is there a better way of making this comparison?
(I wish I could say this was a newbie question, but it's something I've often had trouble with in my years as a designer who tries to code.)
Feel free to edit the question if you know better terminology than I have used here (and let me know what your edits were--I'm having a hard time phrasing the question.).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要引用传递给 mysql 的字符串。
You need to quote strings that you pass to mysql.
运行
以查看您实际发送的查询。
另请阅读
mysql_real_escape_string
以及一般的 SQL 注入。考虑以下您的代码容易出现的非常典型的 SQL 注入示例:Run
to see what query you're actually sending.
Also read up about
mysql_real_escape_string
and about SQL injections in general. Consider the following example of a very typical SQL injection your code is prone to:强烈建议不要将纯 PHP 用于完整的应用程序项目。它使编码员担心基本问题,例如转义查询、验证表单数据、安全性、模板、加载库等。编码员没有担心程序逻辑,而是花太多时间担心语法。只有新手才会这么做。我们不这样做,因为时间对我们来说就是金钱。
我的建议:使用框架。我个人推荐 Codeigniter 或 Zend。相信我,这会让你省去很多头痛。
Using pure PHP for complete application projects is highly discouraged. It puts the coder in the position of worrying about elementary problems such as escaping queries, validating form data, security, templating, loading libraries, etc., etc. Instead of worrying about the program logic the coder puts too much time worrying about the syntax. Only newbies do that. We don't because time is money for us.
My recommendation: use framework. I personally recommend Codeigniter or Zend. Believe me it'll save you a lot of headache.