The easiest way to clean the input for a database!
Posted by DanoDec 13
PHP is a great language, and is full of tons of functions that do just what your asking for quick, fast and in a hurry. 2 of the best functions I’ve come across are:
addslashes()
stripslashes()
These fuinctions are a LIFE SAVER if you are getting form data from your visitors and storing it in your database. Their usage is so simple that I’ve yet to find something easiser todo that beats it. Let’s say your process looks like this:
User Inputs Data –> Page Puts Data in Database — > Page returns user to edit their data
This is a pretty standard process for updating profile data for a social site, or for adding an entry to blog. The usage of these functions really shows their strength here.
When collecting the data use the ADDSLASHES() function to add the escape character to your string preventing the user input from breaking your SQL (such as with apostrophe’s or double quotes!). When you are getting the data back out of the database all you need to do is pass it to the STRIPSLASHES() function before using it and you’ll be good to go! Below is a couple of example code snippets that show the implementation.
//Get User Data Page $username = addslashes($_POST['user_name']); $password = addslashes($_POST['pass_word']); $add_user_sql = "INSERT INTO users (username, password) VALUES ('" . $username . "', '" . $password . "')"; //Show User Data Page $show_user_sql = "SELECT * FROM users WHERE username='hey_you'"; $show_user_result = mysql_query($show_user_sql); $show_user_answer = mysql_fetch_assoc($show_user_result); echo "Username: " . stripslashes($show_user_answer['username']); echo '<br />'; echo "Password: " . stripslashes($show_user_answer['password']); Hope this was helpful, feel free to comment I'm always looking for (worthwhile) improvements.