David Rhoden
David Rhoden

Reputation: 952

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 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.).

Upvotes: 0

Views: 6810

Answers (3)

Jhourlad Estrella
Jhourlad Estrella

Reputation: 3670

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.

Upvotes: 0

sanmai
sanmai

Reputation: 30911

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";

Upvotes: 1

Anze Jarni
Anze Jarni

Reputation: 1157

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

You need to quote strings that you pass to mysql.

Upvotes: 4

Related Questions