PHP is a versatile language, and it is full of many functions that can do just what is needed quick, fast and in a hurry. Two of the best functions I’ve come across are:
You can find these within the PHP manual at:
These functions 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 show/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 . "')";
//Show User Data Page
$show_user_sql = "SELECT * FROM users WHERE username='$username'";
$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']);
Keep in mind the critical success to this, is wrapping your input values within single quotes when building the SQL query.
Hope this was helpful!