开发者

What's the best way to compare variable string equality in PHP/MySQL?

I'm trying to check a string passed through the URL and get back all results from a MySQL database where that str开发者_开发问答ing 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.).


if ($projectsname) {$result = mysql_query("SELECT item FROM items WHERE projectname='$projectsname'",$db)}

You need to quote strings that you pass to mysql.


Run

echo "SELECT item FROM items WHERE projectname=$projectsname";

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:

$projectsname = "123 OR 1=1";
echo "DELETE FROM items WHERE projectname=$projectsname";


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜