tags:

views:

101

answers:

3
$befal = mysql_query("SELECT * FROM users WHERE username = $_GET[username]");
$rad = mysql_fetch_assoc($befal);

Equals

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\profile.php on line 4

I have a user called Admin in the field username and it still dont work. profile.php?user=Admin...

This works if I use the ID though:

$befal = mysql_query("SELECT * FROM users WHERE user_id = $_GET[id]");
$rad = mysql_fetch_assoc($befal);

What can be the problem?

Thanks

+3  A: 

Try it like this:

$befal = mysql_query("SELECT * FROM users WHERE username = '$_GET[username]'");

You have to encapsulate a string parameter in apostrophes.

[UPDATE]

Just like cletus and Olaf pointed out, with the above sql statement you are very prone to SQL Injection. Check out their posted answers to see what I mean.

Andreas Grech
you're welcome mate ;-)
Andreas Grech
I think an upvote is in Order Wiklos.
OscarRyz
upvote requires 15 rep - (s)he's got 3...
Olaf
...and with the update this answer is actually upvotable ;)
Olaf
@Dreas Grech: I suggest you put the big fat warning above your code. I was already on the down-voting button with the mouse for suggesting working but intrinsically broken code.
Tomalak
A: 

Now that you've got your answer, try entering

Something' OR '1' = '1

as username - you've managed to produce a nice SQL-injectable application.

Olaf
should i use mysql_real_escape_string on it first to fix this?
Sorry, I don't know php-functions in depth - cletus suggests mysql_escape_string. See also here: http://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Olaf
+6  A: 

Errr... that's a recipe for getting hacked. I would like to introduce you to SQL injection as characterized by this very funny yet poignant cartoon.

Try this instead.

$username = mysql_escape_string($_GET['username']);
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
cletus
+1 though I probably would have put forward mysqli. And the cartoon is great. *lol*
Tomalak
I've given up on mysqli. Too unstable and noone is fixing the bugs.
cletus
Hm. Admittedly, I don't do enough PHP to have come across any bugs in mysqli. I believe it would work for this trivial scenario, though. ;-) Maybe it's PDO, then. In any case I'm all in favor of prepared/parametrized statements.
Tomalak