0

Possible Duplicate:
Best way to stop SQL Injection in PHP

I have a piece of code that enters code into the database.

Code:

$database->sendUserMessage("You have a new profile comment", "To view your new profile comment, go to your <a href='profile.php?id=$user#comments'>profie</a>.", $user);

INSERT INTO ".TBL_MESSAGES." VALUES (NULL, '$title', '$message', '2', '$user', '0', '0', '0', '0', '0', NULL, NULL, NULL, NULL, now())

The problem i have is when attempting to pass the HTML into the query and execute, it won't execute. However, if I remove HTML, the query works fine.

Is there a way around this?

Thanks.

Community
  • 1
  • 1
sark9012
  • 5,485
  • 18
  • 61
  • 99
  • 1
    While not technically a dupe, your code suffers from a much serious problem than the query not working (it's vulnerable to SQL injection). Luckily for you, you can fix both problems at the same time! Look at the linked question to find out how. **DO NOT USE ANY OTHER APPROACH** -- you 're still learning, so do yourself a favor and follow the practice that practically everyone here on SO recommends. – Jon Sep 12 '11 at 09:56
  • Is it vulnerable even if the user never enters any information? – sark9012 Sep 12 '11 at 10:00
  • If the title *and* the message are *totally generated by your own code* then there's no vulnerability, but: a) "profile comment" does sound like user-provided data and b) this is one of the rare things that you should *always* do, *everywhere*. – Jon Sep 12 '11 at 10:03
  • Ok, I have had a look and taken note. Got it working now. In this case, the system is sending the recipient of the comment a message to alert them. So nothing is being entered by the user, it's auto generated. – sark9012 Sep 12 '11 at 10:05
  • Sure -- but since you didn't protect yourself before, and since you probably do want to protect yourself (from the actual comments), doesn't it make sense to use the correct approach for everything regardless? – Jon Sep 12 '11 at 10:11

2 Answers2

1

you will have to escape you '

mysql_real_escape_string($html)

entire context:

mysql_query("INSERT INTO ".TBL_MESSAGES." VALUES (NULL, '".mysql_real_escape_string($title)."', '".mysql_real_escape_string($message)."', '2', '$user', '0', '0', '0', '0', '0', NULL, NULL, NULL, NULL, now()");
fatnjazzy
  • 6,070
  • 12
  • 57
  • 83
  • Bound parameters are generally a better bet than mysql_real_escape_string, they are less subject to being forgotten. – Quentin Sep 12 '11 at 09:57
  • @Quentin - he did not provide the method he is using the database so i just assumed. – fatnjazzy Sep 12 '11 at 09:58
  • If you are using a method which does not support bound parameters, then change to one that does. – Quentin Sep 12 '11 at 09:59
1

You're injecting your own database! You need to replace the 's with their html entity equivalent. (use the mysql_real_escape_string function)