0
$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

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • Don’t forget to sanatize the data before using it in a database query. – Gumbo Feb 21 '09 at 10:15
  • you should check the return value for mysql_query() and if it fails look at mysql_error(). That should give you some idea of why a query is failing – Tom Haigh Feb 21 '09 at 10:21

3 Answers3

6

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'");
Community
  • 1
  • 1
cletus
  • 616,129
  • 168
  • 910
  • 942
  • +1 though I probably would have put forward mysqli. And the cartoon is great. *lol* – Tomalak Feb 21 '09 at 10:45
  • I've given up on mysqli. Too unstable and noone is fixing the bugs. – cletus Feb 21 '09 at 10:46
  • 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 Feb 21 '09 at 10:55
3

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.

Community
  • 1
  • 1
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • @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 Feb 21 '09 at 10:48
0

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 Kock
  • 46,930
  • 8
  • 59
  • 90
  • should i use mysql_real_escape_string on it first to fix this? –  Feb 21 '09 at 10:21
  • 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 Kock Feb 21 '09 at 10:24