tags:

views:

20

answers:

2

In most cases whenan sql update query is posted my php script, it works without problem. However, in some cases I get an error from mysql. I'm using a encryption function to send data over the net, so it arrives as sent.

If I post the same query into phpmyadmin, it always works.

Do I need to add $sql = addslashes($sql); ?

I'm hesitant to use this on all queries as most of the work and I don't want to end up with slashes in my data when it may not be needed.

A: 

You are not specifying what error exactly you get from mySQL. (Please always, always add the error message and example data.)

I'm going to guess though that the SQL query breaks when the user enters quotes: ' or "

This is a sign of a very dangerous vulnerability called SQL injection.

Do not use addslashes() to fix it, but the escaping method provided by your database layer - probably mysql_real_escape_string().

More info: Best way to defend against mysql injection and cross site scripting

Pekka
he is adding slashes to the entire query, lol. I won't be surprised if he sends a query itself
Col. Shrapnel
I'm not sure what the error is, I don't log it. But it will be due to ' or "" or maybe \. My other system builds up the sql. So theres little danger of sql injection. Could I use mysql_real_escape_string() on my whole sql query ?
Jules
@Jules no, you need to escape the values only
Pekka
@Jules you also want to start logging (or at least displaying) your errors - it'll make your work much easier
Pekka
A: 

mysql_real_escape_string

ex:

$c = mysql_connect("localhost","a","b");
$query = 'SELECT * FROM table WHERE name="%s";'
mysql_query(sprintf($query,mysql_real_escape_string($_POST['name'],$c))); 
Robus
Can I use mysql_real_escape_string() on the full sql statement ?
Jules
Shortly: No. Because you'd also be escaping the quotes which belong into the query.
Robus
mysql_real_escape_string is useless in his case. addslashes is enough
Col. Shrapnel
@Col. Shrapnel Changing this to addslashes barely gives any performance boost, but might lead to leaks later. I'd still stick with mysql_escape
Robus
looooooooooooool. who is talking of "performance"? He does create his query *on the another host*. Try to think of it while keeping in mind how does mysql_real_escape_string work.
Col. Shrapnel
You might want to state your point directly without trying to be witty.
Robus
mysql_real_escape_string does take current database connection character set into account. But the OP does build his query on the another host. Thus, there is no use of mysql_real_escape_string.
Col. Shrapnel