Discuss How to handle slashes in mysql in the PHP Development forum on Dev Shed. How to handle slashes in mysql PHP Development forum discussing coding practices, tips on PHP, and other PHP-related topics. PHP is an open source scripting language that has taken the web development industry by storm.
Posts: 13
Time spent in forums: 1 h 33 m 37 sec
Reputation Power: 0
How to handle slashes in mysql
I have an mysql insert problem that I need some help with. I was trying to insert a record that contained a string that was a file path. I made a mistake when I typed the value into a textbox: "\test_email_archive/xxxx.com/box/inbox/2012-09/"
As you can see I had the slash backwards. When the insert was done the record in mysql was valued:
est_email_archive/emarotta.com/box/inbox/2012-09/, with the "\" and "t" truncated. I assume this occurred because the slash was handled as an escape character.
I tried using addslashes and stripslashes, but I can't seem to get the syntax correct. The question I have is how to handle a situation where a user enters string into a text box with a "\" as part of the string so the value gets correctly entered into mysql (as entered)?
The query I have as it stands is:
$query = 'Insert into Email_StaffPath (StaffID, StaffPath) values(' . $StaffID . ',"' . $StaffPath . '")';
I also tried it reversing the single and double quotes.
$query = "Insert into Email_StaffPath (StaffID, StaffPath) values(" . $StaffID . ",'" . $StaffPath . "')";
Posts: 1,833
Time spent in forums: 1 Month 2 Weeks 1 Day 21 m 25 sec
Reputation Power: 811
Hi,
in addition to what BarryG already said:
this little slash problem points to massive security holes in your query code. When certain characters break the query, there's obviously something wrong. What if people actively use this to mess with your database (aka SQL injection)?
The problem is that you don't separate the actual query from the values you want to pass. It's all just one big string. So if users input a "wrong" value, it could easily interfer with the SQL (which is what just happened). To solve this, use prepared statements, which are available through the MySQLi extension or the PDO interface.
If you're still using the old "mysql_" functions, throw them away. They are long obsolete and will die out sooner or later. If you cannot possibly do that, because you've already written 100,000 lines of code, well, then use mysql_real_escape_string() as suggested by BarryG. But this is really just a workaround for old code. In any other case, use PDO or MySQLi.