Validating and Inserting User Data in PHP/MySQL(i)
Submitted by Yorkiebar on Thursday, July 3, 2014 - 05:56.
Language
Introduction:
This tutorial is on how to take user input, check it against a database, and insert if it is not already present. This could be used for registration in terms of unique usernames.
Database:
First we need a database with one table. My database is called 'fln', table is called 'test', and it has two fields:
id, int, 5 length, primary key, auto increment.
username, varchar/string, 255 length
Connection:
Next we need to make the PHP connection to our database, in mysqli we use the connect function which takes four parameters; the service server name for your MySQL service, username, password, and database name. Like so...
HTML:
Ok. So now we can set up our user input. This is just going to be a simple one textbox and submit button form since the only column I have available in my database table and need for this tutorial's example is the username. My HTML form looks like so...
Ok so now we have the user input username. Next we want to check whether the username already exists within our database table 'test'. We do this through a simple query statement selecting the rows containing the username...
We then count the amount of rows returned. If the rows returned is one (or more, although it shouldn't be more than one) we output that the username already exists, if no rows are returned we insert the username as a new row through a new 'insert' query statement and output accordingly...
Note; we insert a blank value followed the username because my first 'id' column is auto incrementing all by itself.
Finished!
- <?php
- ?>
The above form will send the data to the page I am currently editing, 'validation.php'. It is as a 'POST' method so that no one can edit it through the basic URL encoding.
PHP Data Validation:
Before we can do the validation, we first want to ensure (validate...) that the data is there. We do this by checking for post input of the variable name 'username', we set it to a variable if it is there...
- $user = $_POST['username'];
- }else
- echo 'No username input found. No post sent...';
- echo 'That username already exists.';
- }else{
- if ($insertQuery) {
- echo 'Inserted username successfully!';
- }else
- echo 'Failed to insert username although no rows previously existed...';
- }
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
Add new comment
- 535 views